美文网首页
Python物理建模初学者指南(part I)

Python物理建模初学者指南(part I)

作者: 锅炉工的自我修养 | 来源:发表于2020-08-26 19:11 被阅读0次

    练习代码如下

    # -*- coding: utf-8 -*-
    """
    Spyder Editor
    
    This is a temporary script file.
    """
    import math
    
    
    
    print("Hello, World!")
    a=[1,2,3]
    print(a)
    b={1,2,3,3,4}
    
    print(b)
    print("a type is ",type(a))
    print("b type is ",type(b))
    
    # test for magic command, e.g. %reset equal to clear in matlab
    # magic command use in python console
    
    # test for ;
    a=1;b=2;c,d=[3,4];
    print(a,b,c,d)
    
    # test for \, don't split the variable name into two lines
    co\
    =10
    print(co)
    
    # get help: type? in command line
    help(type)
    
    # get help from web
    import requests
    #from bs4 import BeautifulSoup
    url="https://blog.csdn.net/"
    context=requests.get(url).content
    # soup=BeautifulSoup(context)
    #print(content)
    print("Now, i can't navigate to web. ops")
    
    # round,pow,sqrt, cmd+i 
    t1=round(2**0.5,5)
    t2=2**0.5
    t3=pow(2,0.5)
    t4=math.sqrt(t3)
    print(t1,t2,t3,t4)
    
    print("========== how to know the function belong to which package?")
    
    print(dir(__builtins__))
    
    # 做好问题日志
    import numpy as np
    tmp=np.sqrt(2)
    print('the root of 2 is ',round(tmp,4))
    
    # from ... import *, improt the complete to current envirment
    # from numpy import *
    tmp=np.sqrt(2)
    print('Now sqrt can be use, sqrt(2) is', round(tmp,4))
    # import specified function
    from numpy import exp, log,log10
    tmp=log(exp(1));
    print(tmp)
    tmp=log10(10)
    print(tmp)
    # set the import function a alias
    from numpy.random import random as rng
    print(rng())
    # 1.3.3
    import numpy as np
    # import matplotlib.pyplot as plt
    
    '''python expression'''
    print(123)
    print(2.3e5)
    print(2+3j)
    print(round(np.pi,4))
    
    a,b,c=-1,-1,-1
    # tt=np.sqrt(b**2-4*a*c)
    # print(tt)
    # print(sqrt(-1)) # can't calculate (-1)^0.5
    print(pow(-1,0.5)) # pow can 
    print(dir(np))
    """e,pi,1j,sin,cos"""
    print(np.pi)
    print(np.e)
    print(np)
    print(np.sin(30))
    import cmath as cm
    print(cm.sqrt(-1))
    tmp=complex(1,3)
    print(np.real(tmp))
    print(np.imag(tmp))
    print(np.abs(tmp))
    # use np.pi avoid to modify the value of pi, use long name to clear the meaning of variables
    # set name by addPlus or add_plus
    print('create a random number: ',np.round(np.random.rand(),4))
    print(dir(np))
    print("how to read the package documents")
    print("python has the paramenter of cunction, e.g. f(x=1,y=2), you don't need remember \
          the squence of parameters")
    
    # print(dir(1))
    
    # f.isinteger, s.swapcase, l.reverse, l.pop
    f=2.5
    print('f is a float number, the value is ',f)
    print('is f is a integer? ',f.is_integer())
    s='Hello'
    print("the swapcase of s is ",s.swapcase())
    print('s is string - ',s )
    l=[1,2,3]
    print('l is a list ',l)
    print("The reverse of l is ",l.reverse())
    print("pop: delete the last value of l is",l.pop())
    print("Current list l is ",l)
    
    # object.attribute
    
    # list, tuple and dictonary
    l=[1,'a',3+4j,'Hello world!']
    print("A complex list is ",l)
    t=(2,3)
    print("A tuple is ",t)
    t=(0,)
    print("A tuple has only one element is ",t)
    
    # zeros, ones, eye, shape, size 
    a=np.zeros(4)
    print('zeros(4) function is ',a)
    a=np.zeros((3,5)) # zeros((dim1,dim2))
    print('zeros(3,5) is ',a)
    a=np.zeros((3,1))
    print("zeros((3,1)) is ", a)
    a=np.eye(3) #
    print("eye(3) is ",a)
    print('np.size is the total number of the matrix, and the np.shape specify the dimension information.')
    print("a's size is ",np.size(a))
    print("a's shape is ",np.shape(a))
    
    # rand & random
    a=np.random.rand(3,5)
    print("rand function: ",a)
    a=np.random.random((3,5))
    print("random fucntion: ",a)
    
    # np.sum, mean, std ...
    print("the mean of a is ",a.mean())
    print("the sum of a is ",a.sum())
    print("the std of a is ",a.std())
    
    # np.array
    a=np.array([[2,3,5],[7,11,13]])
    print("input a array: ",a)
    
    # np.arrange np.linspace
    print("arrang(1,10,4) is ",np.arange(1,10,4))
    print("linspace(1,10,11) is ",np.linspace(1,10,11))
    print("logspace(1,3,3) is ",np.logspace(1,3,3))
    
    # conecttion of array: np.hstack, h.vstack
    a=np.zeros((2,3))
    b=np.ones((2,3))
    print("horizontal conect is ",np.hstack([a,b]))
    print("vertical connect is ",np.vstack([a,b]))
    
    # query the array
    a=np.array([2,4,5])
    a[0]
    a[1]=100 
    print("The new value of a is ",a)
    a=np.array([[2,3,5],[7,11,13]])
    a[0][1]
    a[1][2]=100
    print('New array is ',a)
    
    # slice the array
    a=np.arange(10)
    print('arange(1,10) is ',a)
    n=np.shape(a)
    print('size(a,1) is ',n)
    a=np.array([[1,2,3],[4,5,6],[7,8,9]])
    print(a)
    a1=a[0:3:1,2]
    print(a1)
    a1=a[:,0]
    print("a[:,0] is : ",a1)
    a=np.arange(1,10).reshape(3,3)
    print(a)
    print("The first row is ",a[0])
    print("The first cloumn is ",a[:,0])
    print("The first dimension is ", np.size(a,1))
    
    a=np.arange(0,27).reshape(3,3,3)
    print(a)
    print("The first dimension is ", np.size(a,1))
    print("The first dimension is ", np.size(a,1))
    print("The first dimension is ", np.size(a,1))
    
    # test 2D
    a=np.arange(20)
    print("a[:] ",a[:])
    print("a[::] ",a[::])
    print("a[5:15]",a[5:15])
    print("a[5:15:3]",a[5:15:3])
    print("a[5::]",a[5::])
    print("a[:5:]",a[:5:])
    print("a[::5]",a[::5])
    print("a[-10:]",a[-10:])
    print("a[-1:-10:-1]",a[-1:-10:-1])
    a=np.zeros(10)
    a[0:3]=np.ones(3)
    print(a)
    a=np.array([[1,2],[2,1]])
    b=a.flatten()# return a new array
    c=np.ravel(a)# assign by reference
    d=a.ravel()
    print(a)
    print("flatten method: ",b)
    print("ravel method: ",c)
    b[1]=11
    print("new b is ",b)
    print("new a is ",a)
    c[2]=22
    print("nwe c is ",c)
    print("new a is ",a)
    print("ravel method change the value of a array")
    
    # reshape
    a=np.arange(12)
    b=np.reshape(a,(3,4))
    c=a.reshape((3,4))
    print("a.reshape((3,4))",c)
    print("a.reshape((2,3,3))",a.reshape((2,3,2)))
    
    # use list for index of slice
    a=np.arange(10,21)
    print(a)
    b=[2,4,5]
    print("a[b]",a[b])
    print("The first index in python is 0!")
    
    # logic index
    a=np.arange(-10,11)
    print(a)
    less_than_five=(abs(a)<5)
    b=a[less_than_five]
    print("The absolute value less than five is: ",b)
    print("a[abs(a)<5] is",a[abs(a)<5])
    
    # string
    a='let\'s go!'
    print(a)
    s='123'
    pie='3.1415'
    x=int(s)+1
    y=float(pie)+1
    # z_bad=int(s)+int(pie) # 
    z_good=x+y-2
    # print("z_bad: ",z_bad)
    print("z_good: ",z_good)
    print("int function can't convert a float to int")
    print("s + pie is", s+' '+pie)
    s='i love'
    b=str(4545)
    print("(s+b)*5",(s+" "+b+' ')*5)
    
    # latex
    s="Position distribution for \$\\mu\$ = "
    print("Position distribution for \$\\mu\$ = ", s)
    
    # format
    s1="The value of pi is approximately "+str(np.pi)
    s2="The value of {} is approximately {:.5f}".format('pi',np.pi)
    print(s1)
    print(s2)
    s="{1:d} plus {0:d} is {2:d}".format(2,4,2+4)
    print(s)
    print("{n:d} approximately same to specify the position and data type!")
    
    # % 
    print("The value of %s is approximately %.5f" %('pi',np.pi))
    print("The value of {} is approximately {:.5f}".format('pi',np.pi))
    
    # for loop
    b,c=2,-1
    for a in np.arange(-1,2,0.3):
        x=(-b+np.sqrt(b**2-4*a*c))/(2*a)
        print("x= {1:.4f}, a= {0:.4f}".format(a,x))
    print("You can't use tab and space simultaneously for indentation")
    print("The : is important for 'for','while' and 'if...elif...else'")
    for i in range(1,21): print(i,i**3)
    
    
    # while loop
    a,b,c=2,2,-1
    delta=b**2-4*a*c
    while ((delta>=0)&(a>0)):
        x=(-b+np.sqrt(delta))/(2*a)
        print("a= {:.4f}, x= {:.4f}".format(a,x))
        a-=0.3
    print('done')
    
    # long time loop
    for i in range(10**6): 
        if i%10**5==0 :
            print("{:.4f} percent complete ...".format((100*i)/10**6))
            # print("\n") 
    
    # The infinite loop
    # while True:
        # print("Here we go again ...") 
    print("ctrl+c to end the running of scripts")
        
    # matrix operation
    b,c=2,-1
    a=np.arange(-1,2,0.3)
    x=(-b+np.sqrt(b**2-4*a*c))
    print("The root list is ",x)
    # for i in x: print("x is {:.4f}".format(i))
    x=np.exp(a)
    # for i in x: print("x is {:.4f}".format(i))
    
    # 2F
    x=np.arange(-1,1,0.1)
    y=np.exp(-x**2)
    for i in y: print('y(i) is {:.4f}'.format(i))
    
    N=10
    n=np.arange(0,N+1)
    print(n)
    mu=2
    from scipy.special import factorial
    y=exp(-mu)*mu**n/factorial(n,exact=True)
    for i in y : print("y is {:.4f}".format(i))
     
    # dot
    a=np.array([1,2,3])
    b=np.array([1,0.1,0.01])
    c=a*b
    # print("a*b=  {:.4f}".format(c))
    print("a*b= ",c)
    print("sum(a*b) is {:.4f}".format(np.sum(a*b)))
    print("a.b= {:.4f}".format(np.dot(a,b)))
    print("a x b= ",np.cross(a,b)) 
    
    # sum
    a=np.vstack((np.arange(20),np.arange(100,120)) )
    print("The matrix a is ",a)
    b=np.sum(a,0) # sum the column
    c=np.sum(a,1) # sum the row
    d=np.sum(a)
    print("sum of first column is ",b)   
    print("sum of second column is ",c)   
    print("sum of a is ",d)   
    b=a.sum(0)
    print("sum of column is ",b)   
    print("sum(a) is ", sum([1,2,3]))
    print("np.prod is ",np.prod(a))
    print("np.mean is ",a.mean())
    print("np.std is {:.4f}".format(a.std()))
    print("np.min is ",a.min())
    print("np.max is ",a.max())
    print("factorial(10) is ",np.arange(1,11).prod())
    print("factorial function is ",factorial(10,exact=True))
    
    """scripts: '%edit' create a new file """
    print("New magic command: %edit & %run")
    
    

    相关文章

      网友评论

          本文标题:Python物理建模初学者指南(part I)

          本文链接:https://www.haomeiwen.com/subject/tbpfsktx.html