Python工程数学2程序开胃菜(上)

2 数学程序开胃菜

在上一章中( https://mp.weixin.qq.com/s/kKenXcEXIeLd_u_2kymF8A ),我们介绍了python的IDE;用numpy实现向量计算;用Matplotlib绘图;用sympy实现微积分和求导;用SciPy实现积分;用VPython实现弹跳球动画。

在本章中,您将了解 Python 命令式编程风格的线性程序结构以及分支和重复结构。面向对象编程和函数式编程的示例描述了使用 Python 编程的更多方法。

使用计算机解决的问题可以通过编程语言以多种方式建模和结构化。在应用计算机科学领域,命令式(过程式)编程、面向对象编程 (OOP) 和函数式编程风格已经确立。Python 支持所有这三种编程风格。
问题的解决方案也与逻辑条件相关联: 预期情况是否适用?此外,根据问题的不同,必须重复执行相同的任务,例如计算数学函数的值表。与其他过程式编程语言一样,Python 支持线性程序结构以及分支和重复结构。

2.1 线性程序结构

2.1.1 线性程序

  • 实例:计算电流

U=230
R=11.8
I=U/R
b="The current is:"
print(b, I, " A") 

执行:

The current is: 19.491525423728813  A

python的整数是没有大小限制的,浮点数的限制如下:

>>> import sys
>>> print(sys.float_info)
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
  • 实例:计算串联电路的功率
#02_linear2.py
U = 230
R1, R2, R3=0.12, 0.52, 228
Rg = R1 + R2 + R3
I= U/Rg
P1 = R1 * I**2
P2 = R2 * I**2
P3 = R3 * I**2
print("Current I={0:6.3f} A " .format(I))
print("P1={0:3.2f} W, P2={1:3.2f} W, P3={2:3.2f} W".format(P1,P2,P3))

执行:

Current I= 1.006 A 
P1=0.12 W, P2=0.53 W, P3=230.72 W
  • 实例:通过使用内置输入函数获取数值:
#02_linear2.py
U = 230
R1, R2, R3=0.12, 0.52, 228
Rg = R1 + R2 + R3
I= U/Rg
P1 = R1 * I**2
P2 = R2 * I**2
P3 = R3 * I**2
print("Current I={0:6.3f} A " .format(I))
print("P1={0:3.2f} W, P2={1:3.2f} W, P3={2:3.2f} W".format(P1,P2,P3))

执行:

---Input---
Voltage: 220
Resistance: 34

---Output---
Current   6.47 A
Power 1423.53 W

---Input---
Voltage:

参考资料

2.2 函数

  • 实例:使用函数来计算电流、电功率、电功和电能成本:
#04_function1.py
U, R = 230, 460
t = 8
price = 0.3

def current():
    I = U / R
    print("Current: ", I, " A")

def power():
    P = U**2 / R
    print("Power : ", P, " W")

def work():
    P = U**2  /R
    W = P * t
    print("Work: ", W, " Wh")

def cost():
    I = U / R
    W = U * I * t
    c = W * price / 1000.0
    print("Cost: ", c, " Euro")

current()
power()
work()
cost() 

执行:

Current:  0.5  A
Power :  115.0  W
Work:  920.0  Wh
Cost:  0.276  Euro

argument是调用函数时传递的值。该值被分配给函数中的指定参数。parameter是函数中使用的名称。

  • 实例:带返回值的函数
#05_function2.py
def current(U, R):
    return U / R

def power(U, R):
    return U**2/R

def work(U, R, t):
    P = U**2 / R
    W = P*t
    return W

def cost(U, R, t, price):
    I = U / R
    W = U * I * t
    c =W * price / 1000.0
    return c

Uq = 230    #V
RLoad = 23 #ohms
tn = 8      #h, hours
price_actual = 0.3 #euro
print("Current: ", current(Uq, RLoad), " A")
print("Power  : ", power(Uq, RLoad), " W")
print("Work   : ", work(Uq, RLoad,tn), " Wh")
print("Cost   : ", cost(Uq, RLoad,tn,price_actual), " euros") 

执行:

Current:  10.0  A
Power  :  2300.0  W
Work   :  18400.0  Wh
Cost   :  5.52  euros
  • 实例:带有多个返回值的函数:计算出体积、质量、惯性矩和加速力矩

与其他编程语言不同,Python 也允许返回多个值。我们来看一个直径为 1 分米、长度为 10 分米的实心钢圆柱体的例子。只需一个函数,就可以计算出体积、质量、惯性矩和加速力矩。所有四个值都应通过返回语句返回。

加速力矩 Mb 与角加速度 α 和惯性矩 J 成比例增加:

圆柱体的惯性矩 J 与质量m成正比,与半径 r 的平方成正比:

质量m由圆柱体的体积 V 和密度计算得出:

要计算体积 V,需要圆柱体的直径 d 和长度 l:

要完成这项任务,必须在 Python 开发环境的文本编辑器中按照语法规则以相反的顺序输入公式。

#06_function3.py
rho = 7.85   #kg/dm^3, density for steel
alpha = 1.2  #1/s^2, angular acceleration
g = 3        #accuracy

def cylinder(d,l):
    V=round(0.785*d**2*l,g)
    m=round(rho*V,g)
    J=round(0.5*m*(d/2/10)**2,g)
    Mb=round(alpha*J,g)
    return (V,m,J,Mb)
    #return V,m,J,Mb
    #return [V,m,J,Mb]

d1=1  #dm
l1=10 #dm
T=cylinder(d1, l1)
print("Cylinder data: ", T)
print("Volume:             ", T[0]," dm^3")
print("Mass:               ", T[1]," kg")
print("Moment of inertia:  ", T[2]," kgm^2")
print("Acceleration torque:", T[3]," Nm") 

执行:

Cylinder data:  (7.85, 61.622, 0.077, 0.092)
Volume:              7.85  dm^3
Mass:                61.622  kg
Moment of inertia:   0.077  kgm^2
Acceleration torque: 0.092  Nm
  • 实例:函数嵌套调用:
#07_function4.py
rho=7.85    #kg/dm^3, density of steel

def volume(d,l):
    return 0.785*d**2*l

def mass(d,l):
    return rho*volume(d,l)

def moment_of_inertia(d,l):
    return 0.5*mass(d,l)*(d/2/10)**2

def acceleration_torque(d,l,alpha):
    return alpha*moment_of_inertia(d,l)

d1=1 #dm
l1=10 #dm
alpha1=1.2 #1/s^2, angular acceleration
V=volume(d1,l1)
m=mass(d1,l1)
J=moment_of_inertia(d1,l1)
Mb=acceleration_torque(d1,l1,alpha1)
print("Volume: ", V, " dm^3")
print("Mass: ", m, " kg")
print("moment of inertia: ", J, " kgm^2")
print("Acceleration torque: ", Mb, " Nm")

执行:

Volume:  7.8500000000000005  dm^3
Mass:  61.6225  kg
moment of inertia:  0.07702812500000002  kgm^2
Acceleration torque:  0.09243375000000002  Nm

2.3 分支结构

  • 实例:解一元二次方程


根下的表达式也可以取负值。当出现这种情况时,方程将无法在实数空间内求解。因此,程序必须通过检查 D 是否≥ 0 来捕捉这种情况。对于要解决的问题,可以创建如图 2.3 所示的结构图。

#08_branch1.py
import math as m
p=-8.
q=7.
D=(p/2)**2 - q
if D >= 0:
    x1 = -p/2 + m.sqrt(D)
    x2 = -p/2 - m.sqrt(D)
    print("x1 =",x1,"\nx2 =",x2)
    print("p =",-(x1+x2),"\nq =",x1*x2)
else:
    print("The equation cannot be solved!")

执行:

x1 = 7.0 
x2 = 1.0
p = -8.0 
q = 7.0
  • 实例:多重选择

#09_multiple_selection1.py
color=["black", "brown", "red", "orange", "yellow",
       "\ngreen","blue","purple","gray","white"]
code="yellow"       #input
if code==color[0]:
    print("The color black is coded as 0.")
elif code==color[1]:
    print("The color brown is coded as 1.")
elif code==color[2]:
    print("The color red is coded as 2.")
elif code==color[3]:
    print("The color orange is coded as 3.")
elif code==color[4]:
    print("The color yellow is coded as 4.")
elif code==color[5]:
    print("The color green is coded as 5.")
elif code==color[6]:
    print("The color blue is coded as 6.")
elif code==color[7]:
    print("The color purple is coded as 7.")
elif code==color[8]:
    print("The color gray is coded as 8.")
elif code==color[9]:
    print("The color white is coded as 9.")

执行:

The color yellow is coded as 4.
  • 实例:电费费率
#10_multiple_selection2.py
rate1,rate2,rate3=0.3,0.25,0.2 #euros
consumption=5500 #kWh

if 0 < consumption<= 5000:
    print("Amount for rate1:",consumption*rate1, "euros")
elif 5000 < consumption <= 10000:
    print("Amount for rate2:",consumption*rate2, "euros")
elif 10000 < consumption <= 30000:
    print("Amount for rate3:",consumption*rate3, "euros")
else:
    print("industry_rate!")

执行:
```python
Amount for rate2: 1375.0 euros