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

news/2024/10/1 8:52:12

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:

参考资料

  • 软件测试精品书籍文档下载持续更新 https://github.com/china-testing/python-testing-examples 请点赞,谢谢!
  • 本文涉及的python测试开发库 谢谢点赞! https://github.com/china-testing/python_cn_resouce
  • python精品书籍下载 https://github.com/china-testing/python_cn_resouce/blob/main/python_good_books.md
  • Linux精品书籍下载 https://www.cnblogs.com/testing-/p/17438558.html

2.2 函数

  • 实例:使用函数来计算电流、电功率、电功和电能成本:
#04_function1.py
U, R = 230, 460
t = 8
price = 0.3def current():I = U / Rprint("Current: ", I, " A")def power():P = U**2 / Rprint("Power : ", P, " W")def work():P = U**2  /RW = P * tprint("Work: ", W, " Wh")def cost():I = U / RW = U * I * tc = W * price / 1000.0print("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 / Rdef power(U, R):return U**2/Rdef work(U, R, t):P = U**2 / RW = P*treturn Wdef cost(U, R, t, price):I = U / RW = U * I * tc =W * price / 1000.0return cUq = 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        #accuracydef 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 steeldef volume(d,l):return 0.785*d**2*ldef mass(d,l):return rho*volume(d,l)def moment_of_inertia(d,l):return 0.5*mass(d,l)*(d/2/10)**2def 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 #kWhif 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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ryyt.cn/news/66721.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

河道水位识别系统

河道水位识别系统采用视频智能分析功能,河道水位识别系统利用前端摄像头实时获取前端视频视频后,自动识别水尺位置,并在水尺区域将水尺进行数字分割,河道水位识别系统然后再通过水位线的位置,通过AI图像识别技术将数字与水位线位置结合对别,即可识别出水尺读数。河道水位…

自动识别是否穿着工作服

自动识别是否穿着工作服通过AI视频分析技术,自动识别是否穿着工作服对作业区域现场人员工作服是否穿戴进行7*24小时实时监测。自动识别是否穿着工作服监测到现场有人未穿戴工作服时,不需人为干预立即抓拍告警,并联动音箱提醒现场人员穿戴工作服。自动识别是否穿着工作服代替…

河道采砂实时监测系统

河道采砂实时监测系统通过opencv网络模型技术,河道采砂实时监测系统能够对河道两岸非法采砂船进行7*24小时自动检测识别,河道采砂实时监测系统发现违规采砂行为(采砂船),不需人为干预自动告警同步回传给后台通知后台值班人员及时制止。河道采砂实时监测系统通过AI技术手段…

学校食堂互联网明厨亮灶智能监控系统

学校食堂互联网明厨亮灶智能监控系统通过AI识别分析技术,学校食堂互联网明厨亮灶智能监控系统对学校食堂餐厅监控画面开展实时检测,学校食堂互联网明厨亮灶智能监控系统对后厨厨师没有按照餐厅要求佩戴厨师帽厨师服口罩,更有甚者在厨房违规抽烟以及玩手机等行为,学校食堂互…

垃圾桶溢出识别监测系统

垃圾桶溢出识别监测系统通过计算机视觉技术,垃圾桶溢出识别监测系统对社区街道垃圾桶里面垃圾溢出满载现象进行自动识别,垃圾桶溢出识别监测系统监测到社区或者街道垃圾桶里面垃圾溢出时,不需人为干预可以立即告警提醒后台值班人员及时清理。垃圾桶溢出识别监测系统通过AI视…

C#/.NET/.NET Core开发实战教程集

DotNetGuide介绍 DotNetGuide是一个专注于C#/.NET/.NET Core学习、工作、面试指南的GitHub知识库,该知识库在GitHub中Star数已突破6.5k+当然这离不开各位小伙伴的支持和鼓励。该知识库记录、收集和总结C#/.NET/.NET Core基础知识、学习路线、开发实战、编程技巧练习、学习视频…

VMware ESXi 8.0U3b macOS Unlocker OEM BIOS 2.7 Dell HPE 定制版 9 月更新发布

VMware ESXi 8.0U3b macOS Unlocker & OEM BIOS 2.7 Dell HPE 定制版 9 月更新发布VMware ESXi 8.0U3b macOS Unlocker & OEM BIOS 2.7 Dell HPE 定制版 9 月更新发布 VMware ESXi 8.0U3b macOS Unlocker & OEM BIOS 2.7 标准版和厂商定制版 ESXi 8.0U3 标准版,De…

VMware Tanzu Kubernetes Grid Integrated Edition (TKGI) 1.20.0 - 运营商 Kubernetes 解决方案

VMware Tanzu Kubernetes Grid Integrated Edition (TKGI) 1.20.0 - 运营商 Kubernetes 解决方案VMware Tanzu Kubernetes Grid Integrated Edition (TKGI) 1.20.0 - 运营商 Kubernetes 解决方案 Kubernetes-based container solution with advanced networking, a private con…