computation for physics 計算物理概論 introduction to numpy and scipy

24
Computation for Physics 計計計計計計 Introduction to NumPy and SciPy

Upload: willis-watts

Post on 29-Dec-2015

263 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

Computation for Physics計算物理概論

Introduction to NumPy and SciPy

Page 2: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

List v.s. Array (numpy package)

• List– Variable length, you can add or remove elements.– Elements can be of different types.– Flexible.

• Array– The number of elements is fixed.– The elements must be of the same type.– Behave roughly like vectors and matrices.– Faster.

Page 3: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

1D Array

>>>from numpy import zeros>>>a = zeros(4, float)>>>print(a)[0. 0. 0. 0.]>>>a = zeros(5, float)>>>print(a)[0 0 0 0 0]>>>a = zeros(3,complex)>>>print(a)

Page 4: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

2D Array

>>>a = zeros([3,4],float)>>>print(a)[[ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.]]

Page 5: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

Array Initialization in NumPy

• zeros– Create an array with all elements equal to zero.

• ones– Create an array with all elements equal to one.

• empty– Create an empty array. (Faster.)– In practice the aren't empty. (Random stuff in the

memory).

Page 6: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

List Array List

>>>r = [1.0, 1.5, -2.2]>>>a = array(r,float)>>>a = array([1.0, 1.5, -2.2], float)>>>print(a[0])1.0>>>a = array([[1,2,3],[4,5,6]], int)>>>print(a)[[ 1 2 3] [ 4 5 6]]>>>print(a)>>>r = list(a)

Page 7: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

Accessing and Modifying Elements

>>>a = array([1.0, 1.5, -2.2], float)>>>a[0]1.0>>>a[2]=4 (4 will be converted into float)

>>>a = array([[1,2,3],[4,5,6]], int)>>>a[0][1]2>>>a[0][1]=0>>>print(a)[[ 1 0 3] [ 4 5 6]]

Page 8: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

Reading a 1D Array from a File

values.txt1.01.5-2.22.6

>>>from numpy import loadtxt>>>a = loadtxt("values.txt", float)>>>print(a)[ 1. 1.5 -2.2 2.6]

Page 9: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

Reading a 2D Array from a File

values.txt1 2 3 43 4 5 65 6 7 8

>>>from numpy import loadtxt>>>a = loadtxt("values.txt", float)>>>print(a)[[ 1. 2. 3. 4.] [ 3. 4. 5. 6.] [ 5. 6. 7. 8.]]

Page 10: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

Arithmetic with Arrays

>>>a[0] = a[1] + 1>>>x = a[2]**2 -2*a[3]/y>>>r = [1,2,3,4]>>>a = array(r, int)>>>s = 2*r>>>b = 2*a>>>print(s)[1,2,3,4,1,2,3,4]>>>print(b)[2 4 6 8]

Page 11: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

Add or Subtract Two Arrays

>>>a = array([1,2,3,4],int)>>>b = array([2,4,6,8],int)>>>print(a+b)[3 6 9 12]>>>print(b-a)[1 2 3 4](Two arrays must have the same size)>>>>print(a+1)

Page 12: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

Multiply Two Arrays ≠ Dot Product

>>>a = array([1,2,3,4],int)>>>b = array([2,4,6,8],int)>>>print(a*b)[2 8 18 32]>>>print(b/a)[2.0 2.0 2.0 2.0]

Page 13: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

"Dot Product" of Two 1D Arrays="Inner Product"

>>>from numpy import array, dot>>>a = array([1,2,3,4],int)>>>b = array([2,4,5,8],int)>>>print(dot(a,b))60

Page 14: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

"Dot Product" of Two 2D Arrays = "Matrix Product"

>>>a = array([[1,3],[2,4]],int)>>>b = array([[4,-2],[-3,1]],int)>>>c = array([[1,2],[2,1]],int)>>>print(dot(a,b)+2*c)[[-3 5] [ 0 2]]

(1 32 4)( 4 −2

−3 1 )+2(1 22 1)=(−3 5

0 2)

Page 15: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

Array Functions• Most list functions can be applied to 1D array– sum– max– min– len

• You can also apply math functions>>>a = array([1,2,3,4],float)>>>print(sin(a))[0.84147098 0.90929743 0.14112001 -0.7568025]

Page 16: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

Array Methods

>>>a = array([1,2,3,4],float)>>>a.size4>>>a.shape(4,)>>>a = array([[1,2,3],[4,5,6],int)>>>a.size6>>>a.shape(2,3)

Page 17: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

Try: Average of a Set of Values in a File

• A set of numbers stored in a file values.txt.• We don't know how many numbers there are.• Want to calculate their mean.

Page 18: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

Mean and Mean-Square

from numpy import loadtxtvalues = loadtxt("values.txt",float)mean = sum(values)/len(values)mean_sqr = sum(values*values)/len(values)print(mean)print(mean_sqr)

Page 19: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

Geometric Mean

from numpy import loadtxt,log,expfrom math import log,expvalues = loadtxt("values.txt",float)geometric=exp(sum(log(values))/len(values))print(geometric)

𝑥=[∏𝑖=1

𝑛

𝑥 𝑖]1 /𝑛

→𝑥=𝑒𝑥𝑝( 1𝑛∑𝑖=1𝑛

𝑙𝑛 (𝑥 𝑖 ))

Page 20: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

numpy.arange• arange([start],stop[,step],dtype=None)

– Return evenly spaced values within a given interval.– Values are generated within the half-open interval [start, stop) (in other

words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list.

– When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use linspace for these cases.

>>> np.arange(3)array([0, 1, 2])>>> np.arange(3.0)array([ 0., 1., 2.])>>> np.arange(3,7)array([3, 4, 5, 6])>>> np.arange(3,7,2)array([3, 5])

Page 21: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

numpy.linspace

• Return evenly spaced numbers over a specified interval.– Return evenly spaced numbers over a specified interval.– Returns num evenly spaced samples, calculated over the

interval [start, stop ].

– The endpoint of the interval can optionally be excluded.>>>linspace(2.0, 3.0, num=5)array([ 2., 2.25, 2.5, 2.75, 3. ])>>>linspace(2.0, 3.0, num=5, endpoint=False)array([ 2. , 2.2, 2.4, 2.6, 2.8])>>>linspace(2.0, 3.0, num=5, retstep=True)(array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)

Page 22: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

numpy.random

• import numpy.random– numpy.random.random()

• from numpy.random import random– random()

• from numpy.random import *– random()

Page 23: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

numpy.random• seed([seed])• get_state()• set_state(state)• random(size)=random_sample(size)=ranf([size])=sample([

size])– Return random floats in the half-open interval [0.0, 1.0).

• randint(low,high=None,size=None)– Return random integers from low (inclusive) to high

(exclusive).• choice(a[,size,replace,p])• shuffle(X)• permutation(X)

Page 24: Computation for Physics 計算物理概論 Introduction to NumPy and SciPy

Try: Random Number

• Input N.• Generate N random numbers.• Output the mean and the standard deviation.