Python实现数值积分方式
作者:MachineRandy 时间:2022-01-23 14:00:37
原理:
利用复化梯形公式,复化Simpson公式,计算积分。
步骤:
import math
"""测试函数"""
def f(x,i):
if i == 1:
return (4 - (math.sin(x)) ** 2) ** 0.5
if i == 2:
if x == 0:
return 1
else:
return math.sin(x) / x
if i == 3:
return (math.exp(x)) / (4 + x ** 2)
if i == 4:
return math.log(1+x,math.e) / (1 + x ** 2)
"""打印显示函数"""
def p(i,n):
return "第" + str(i) + "题,n=" + str(n) + "时的积分值为:"
"""复化Simpson函数"""
def Simpson(a, b, n, i):
h = (b - a) / (2 * n)
F0 = f(a,i) + f(b,i)
F1 = 0
F2 = 0
for j in range(1,2 * n):
x = a + (j * h)
if j % 2 == 0:
F2 = F2 + f(x,i)
else:
F1 = F1 + f(x,i)
SN = (h * (F0 + 2 * F2 + 4 * F1)) / 3
print("复化Simpson函数" + p(i,n) + str("%-10.7f"%(SN)))
return SN
def T(a, b, n, i):
h = (b - a) / n
F0 = f(a,i) + f(b,i)
F = 0
for j in range(1,n):
x = a + (j * h)
F = F + f(x,i)
SN = (h * (F0 + 2 * F)) / 2
print("复化梯形函数" + p(i,n) + str("%-10.7f"%(SN)))
return SN
def SimpsonTimes(x):
n = 1
y = Simpson(0, math.pi/4, n, 1)
while(abs(y - 1.5343916) > x):
n = n + 1
y = Simpson(0, math.pi/4, n, 1)
else:
return n
def Times(x):
n = 1
y = T(0, math.pi/4, n, 1)
while(abs(y - 1.5343916) > x):
n = n + 1
y = T(0, math.pi/4, n, 1)
else:
return n
"""
测试部分
"""
Simpson(0, math.pi/4, 10, 1)
Simpson(0, 1, 10, 2)
Simpson(0, 1, 10, 3)
Simpson(0, 1, 10, 4)
Simpson(0, math.pi/4, 20, 1)
Simpson(0, 1, 20, 2)
Simpson(0, 1, 20, 3)
Simpson(0, 1, 20, 4)
T(0, math.pi/4, 10, 1)
T(0, 1, 10, 2)
T(0, 1, 10, 3)
T(0, 1, 10, 4)
T(0, math.pi/4, 20, 1)
T(0, 1, 20, 2)
T(0, 1, 20, 3)
T(0, 1, 20, 4)
print("复化梯形函数求解第一问,精度为0.00001时需要" + str(Times(0.00001)) + "个步数")
print("复化Simpson函数求解第一问,精度为0.00001时需要" + str(SimpsonTimes(0.00001)) + "个步数")
print("复化梯形函数求解第一问,精度为0.000001时需要" + str(Times(0.000001)) + "个步数")
print("复化Simpson函数求解第一问,精度为0.000001时需要" + str(SimpsonTimes(0.000001)) + "个步数")
来源:https://blog.csdn.net/MachineRandy/article/details/82634757
标签:Python,数值,积分
0
投稿
猜你喜欢
Django中modelform组件实例用法总结
2023-09-28 14:35:49
Python开发装包八种方法详解
2021-01-12 22:27:28
Javascript typeof 用法
2013-10-20 20:49:40
selenium+python自动化测试环境搭建步骤
2021-03-16 02:34:34
Python中asyncio模块的深入讲解
2022-05-18 22:33:53
Python 操作文件的基本方法总结
2021-11-29 03:18:27
Php中用PDO查询Mysql来避免SQL注入风险的方法
2023-07-18 06:37:42
Python随机数模块详情
2021-10-26 06:47:34
常用的三种修改mysql最大连接数的方法
2010-03-09 15:42:00
python正则表达式中的括号匹配问题
2023-07-26 01:36:24
python pip源配置,pip配置文件存放位置的方法
2023-01-25 09:51:46
RDFa介绍——构建更友好的web页面
2009-09-19 17:01:00
DelphiXE连接MySQL5.1
2010-12-08 16:44:00
WML初级教程之从实际应用中了解WML
2008-09-04 11:24:00
CPQuery 解决拼接SQL的新方法
2012-11-30 20:01:46
Python中常见的数据类型小结
2022-03-25 07:55:17
如何在js中使用FileSystemObject(fso)
2007-09-23 09:10:00
基于Linux系统中python matplotlib画图的中文显示问题的解决方法
2022-05-22 01:34:28
实现一个获取元素样式的函数getStyle
2009-02-10 10:37:00
对Python subprocess.Popen子进程管道阻塞详解
2022-10-30 07:59:49