利用自定义积分公式,目前可以求出所有1元方程和1元积分的近似值

import math, time

def F(x, k):

return 1 + x**k + x

def o(eq, a, b, d=1e-1, max_k=50):

exec(f"g=lambda x:{eq}", globals())

r, s = 0.0, [(a, b)]

while s:

n = []

for x0, x1 in s:

dx = x1 - x0

if dx < d:

x_mid = (x0 + x1) / 2

ws, vs = 0.0, 0.0

for k in range(1, max_k+1):

fv = F(x_mid/(2*math.pi), k)

w = 1/(fv + 1e-12)

ws += w

vs += w * g(x_mid)

val = vs/ws if ws>0 else g(x_mid)

r += dx * val

continue

u, v, m_val = g(x0), g(x1), g((x0+x1)/2)

if abs(u - v) < 1e-8 and abs(m_val - u) < 1e-8:

r += dx * m_val

continue

h = dx / 10

for i in range(10):

n.append((x0 + i*h, x0 + (i+1)*h))

s = n

return r

def so(eq, target, a, b, p, tol=1e-10, max_iter=20):

res_eq = f"abs({eq}-{target})"

x_best = (a + b)/2

min_res = o(res_eq, a, b, d=1e-1)

for _ in range(max_iter):

mid = (a + b)/2

res_a = o(res_eq, a, mid, d=1e-1)

res_b = o(res_eq, mid, b, d=1e-1)

if res_a < res_b:

b, min_res = mid, res_a

else:

a, min_res = mid, res_b

x_best = (a + b)/2

ws, xs = 0.0, 0.0

for k in range(1, 101):

fv = F(x_best/p, k)

w = 1/(fv + 1e-12)

ws += w

xs += w * x_best

x_best = xs/ws if ws>0 else x_best

if b - a < tol:

break

return x_best

test_eq = "200*math.sin(x)**100"

print("积分功能测试")

t0 = time.time()

integral_res = o(test_eq, 1, 200)

t1 = time.time() - t0

print(f"∫[1,200]({test_eq})dx = {integral_res:.12f}")

print(f"积分耗时: {t1:.6f}秒\n")

test_cases = [(1.0, 0.1), (2.0, 0.5), (3.0, 0.8), (0.5, 0.3), (5.0, 0.9)]

print(f"{'M':>3} {'e':>6} {'积分法求出的E':>12}")

for M, e in test_cases:

积分法求解:方程为 E - e*sin(E) = M,变量E∈[0,2π]

eq = f"x - {e}*math.sin(x)"

tf = time.time()

E_f = so(eq, M, 0, 2*math.pi, 10, tol=1e-10)

tf = time.time() - tf

print(f"{M:6.2f} {e:6.2f} {E_f:12.8f}")

print(f"自创积分法时间:{tf}")

相关推荐
噎住佩奇11 分钟前
(Win11系统)搭建Python爬虫环境
爬虫·python
basketball61616 分钟前
python 的对象序列化
开发语言·python
rgeshfgreh38 分钟前
Python流程控制:从条件到循环实战
前端·数据库·python
luoluoal42 分钟前
基于python大数据的电影市场预测分析(源码+文档)
python·mysql·django·毕业设计·源码
幻云20101 小时前
Python深度学习:从入门到实战
人工智能·python
Zoey的笔记本1 小时前
敏捷与稳定并行:Scrum看板+BPM工具选型指南
大数据·前端·数据库·python·低代码
开开心心就好2 小时前
图片格式转换工具,右键菜单一键转换简化
linux·运维·服务器·python·django·pdf·1024程序员节
骥龙2 小时前
1.2下、工欲善其事:物联网安全研究环境搭建指南
python·物联网·安全
Lxinccode3 小时前
BUG(20) : response.text耗时很久, linux耗时十几秒, Windows耗时零点几秒
python·bug·requests·response.text·response.text慢
智航GIS3 小时前
11.2 Matplotlib 数据可视化教程
python·信息可视化·matplotlib