利用自定义积分公式,目前可以求出所有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}")

相关推荐
xcLeigh1 天前
Python入门:Python3 requests模块全面学习教程
开发语言·python·学习·模块·python3·requests
xcLeigh1 天前
Python入门:Python3 statistics模块全面学习教程
开发语言·python·学习·模块·python3·statistics
YongCheng_Liang1 天前
从零开始学 Python:自动化 / 运维开发实战(核心库 + 3 大实战场景)
python·自动化·运维开发
鸽芷咕1 天前
为什么越来越多开发者转向 CANN 仓库中的 Python 自动化方案?
python·microsoft·自动化·cann
秋邱1 天前
用 Python 写出 C++ 的性能?用CANN中PyPTO 算子开发硬核上手指南
开发语言·c++·python
wazmlp0018873691 天前
python第三次作业
开发语言·python
深蓝电商API1 天前
住宅代理与数据中心代理在爬虫中的选择
爬虫·python
历程里程碑1 天前
普通数组----合并区间
java·数据结构·python·算法·leetcode·职场和发展·tornado
weixin_395448911 天前
mult_yolov5_post_copy.c_cursor_0205
c语言·python·yolo
执风挽^1 天前
Python基础编程题2
开发语言·python·算法·visual studio code