<jupyter_start><jupyter_text>Numpyfrom [numpy.org](https://numpy.org):* a powerful N-dimensional array object* sophisticated (broadcasting) functions* tools for integrating C/C++ and Fortran code* useful linear algebra, Fourier transform, and random number capabilities<jupyter_code>import numpy as np

x = np.array([1,2,4])
print(x)
print(x.dtype)

y = np.array([[1,2,3]], dtype=np.float64)
print(y)
print(y.dtype)

print(x.shape, y.shape)
a = np.arange(1, 10, 2)   # similar to range but yields an array

print(a)

b = np.linspace(0, 1, 10) 
print(b)

c, dc = np.linspace(0, 1, 10, endpoint=False, retstep=True)
print(c, dc)
# iterating works just as with lists

for xi in x:
    print(xi)
    
y = np.array([[1, 2, 3], [4, 5, 6]])
for yi in y:
    print(yi)
# computations with arrays are per element per default

z = 2*x**2 - 3*x  
print(z)
print(np.sin(y))

M = np.ones((3,3), dtype=np.float64) # try also zeros, empty
print(M*M)
print(M@M)
from math import sin
N = 1_000_000
xl = [i/(N-1) for i in range(N)]
xa = np.linspace(0, 1, N)
fl = lambda x: [sin(xi) for xi in x]
fa = lambda x: np.sin(x)
%timeit fl(xl)
%timeit fa(xa)
%matplotlib inline
import matplotlib.pyplot as plt

t = np.linspace(0, 1, 200)
y = np.sin(2*np.pi*t)

plt.plot(t, y)
plt.xlabel("$t_t$")
plt.show()
x = np.cos(2*np.pi*t)

plt.subplot(111, aspect='equal')
plt.plot(x, y)
plt.show()<jupyter_output><empty_output><jupyter_text>Array SlicingSyntax: ARRAYNAME[START:STOP:STEP]; Defaults: START=0, STOP=len(ARRAYNAME), STEP=1<jupyter_code>x = np.arange(20)
print("x:", x)
print("x from 2 to 15(excluding):", x[2:15])
print("x from 2 to 15(excluding) in steps of 2:", x[2:15:2])
# negative values
print("x backwards:", x[::-1])
print("x from 1 to 17 (19-2):", x[1:-2])
# now its harder:
print("x from the last element to the fifth last (excluding), backwards:", x[-1:-5:-1])
x = x**2
print("x is now x^2:", x)
print("Differences in x:", x[1:]-x[:-1])          # or just np.diff(x)
print("mean of every neighboring two:", (x[:-1:2]+x[1::2])/2)<jupyter_output>x is now x^2: [  0   1   4   9  16  25  36  49  64  81 100 121 144 169 196 225 256 289
 324 361]
Differences in x: [ 1  3  5  7  9 11 13 15 17 19 21 23 25 27 29 31 33 35 37]
mean of every neighboring two: [  0.5   6.5  20.5  42.5  72.5 110.5 156.5 210.5 272.5 342.5]<jupyter_text>Random numbers<jupyter_code>x = np.random.rand(10)   # 10 random numbers in [0,1)
print("Random numbers:", x)<jupyter_output>Random numbers: [0.08341586 0.1851669  0.49939918 0.17541029 0.3768113  0.18735186
 0.53998326 0.6874538  0.40818619 0.46158486]<jupyter_text>Useful array methods<jupyter_code>print("Sum of all x:", x.sum())
print("Mean value of x:", x.mean())
print("Standard deviation of x:", x.std())
print("Variance of x:", x.var())
print("Minimum of x:", x.min())
print("Maximum of x:", x.max())
print("Index of the minimums in x:", x.argmin())
print("Index of the maximums in x:", x.argmax())<jupyter_output>Sum of all x: 3.6047635017196376
Mean value of x: 0.3604763501719638
Standard deviation of x: 0.18518098770642866
Variance of x: 0.03429199820792848
Minimum of x: 0.08341586159188819
Maximum of x: 0.6874538023718832
Index of the minimums in x: 0
Index of the maximums in x: 7<jupyter_text>ExerciseWrite a program to integrate the function $\int_0^{\pi/2}\sin(x) dx$ using the trapez method:$$ \int_a^b f(x) dx \approx \frac{b-a}{2(N-1)} \sum_{n=1}^{N-1} (f(x_n)+f(x_{n+1}))$$Chose different step sizes and compare the result to the analytical solution.Optional: try a non constant spacing with:$$ \int_a^b f(x) dx \approx \frac{1}{2} \sum_{n=1}^N (x_{n+1}-x_{n})(f(x_n)+f(x_{n+1}))$$<jupyter_code>x = np.array([4,2,6,2,5])
ind = x.argsort()
print("Indices to sort x:", ind)
print("sorted version of x:", x[ind])
print("but x is unchanged:", x)
x.sort()
print("now x is sorted inplace:", x)
print(x)
print(x[[0,3,4]])
x[[0,3,4]] = 1
print(x)
print(x[x>.5])
x[x>.5] = .5
print(x)
# other array construction functions:
print("Linear equidistant:", np.linspace(0.0, 1.0, 10))      # start, stop, count
print("Logarithmic equidistant:", np.logspace(1.0, 5.0, 10)) # start, stop, count
# initialized Arrays; Syntax is the same for all of them:
print("Zeros:", np.zeros(10, dtype=np.complex128))
print("Ones:", np.ones((5,2), dtype=np.int32))        # 5x2 array
print("Empty:", np.empty(10))                         # do not use theses numbers!<jupyter_output>Zeros: [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]
Ones: [[1 1]
 [1 1]
 [1 1]
 [1 1]
 [1 1]]
Empty: [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]<jupyter_text>ExerciseGenerate an array of values with $\sin(x)$ for $x\in [0, 2\pi]$ and 200 points equidistantly spaced. Now clip these values to the range $[-.5, .5]$. This means all values smaller than -.5 must be set to -.5 and all values larger than .5 are set to .5.<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 200)
y = np.sin(x)
plt.plot(y.copy())<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1774354870974195, 'fraction_numerical': 0.10262052410482096, 'mean_word_length': 4.319148936170213, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 23, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '542263', 'license': 'MIT', 'n_tokens_mistral': 2386, 'n_tokens_neox': 2056, 'n_words': 617, 'path': 'projects/winter-school-numerics/Python4NumSim02.ipynb', 'repo_name': 'alayoalex/data-science-ml-portfolio', 'size': '4999'}