鱼C论坛

 找回密码
 立即注册
查看: 546|回复: 2

python积分求助

[复制链接]
发表于 2024-6-5 16:12:17 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. from mpmath import *
  2. import math

  3. mp.dps = 53

  4. def f(x):
  5.     return 3 * x ** 2 + 181 * x - 312

  6. def g(x):
  7.     return exp(2 * x) + log10(x ** 2 + 5 * x) + 32 * x - 201

  8. def product_fg(x):
  9.     return f(x) * g(x)
  10. a = mp.mpf(input("Please enter the lower limit of integration (0.0001 < a < 10000): "))
  11. b = mp.mpf(input("Please enter the upper limit of integration (0.0001 < b < 10000): "))

  12. result = quad(product_fg, [a, b], method='tanh-sinh', epsabs=1e-15, epsrel=1e-15)
  13. integral, error = result
  14. print(f"The result of integration is:{integral}")  
  15. print(f"The error is estimated as:{error}")
复制代码

一直报错显示TypeError: cannot unpack non-iterable mpf object,搞不懂

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-6-5 16:12:29 | 显示全部楼层
这个报错是因为 `quad` 函数返回的结果是一个元组,你需要使用适当的变量来接收返回的值。在这里,`result` 是一个包含积分结果和误差的元组。你可以使用下划线 `_` 来表示你不关心的变量。请将最后几行代码修改为以下方式:

  1. result, _ = quad(product_fg, a, b, method='tanh-sinh', epsabs=1e-15, epsrel=1e-15)
复制代码


现在,积分结果将被正确地赋值给 `result`,而误差将被忽略。然后你可以打印积分结果,并可选地打印误差。

另外,请确保你已经安装了 `mpmath` 这个第三方库,如果没有安装的话可以通过运行以下命令进行安装:

  1. pip install mpmath
复制代码


希望对你有帮助!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-6-5 19:57:23 | 显示全部楼层

回帖奖励 +2 鱼币

  1. from mpmath import *
  2. import math

  3. # 设置高精度
  4. mp.dps = 53

  5. # 定义函数f
  6. def f(x):
  7.     return 3 * x ** 2 + 181 * x - 312

  8. # 定义函数g
  9. def g(x):
  10.     return exp(2 * x) + log10(x ** 2 + 5 * x) + 32 * x - 201

  11. # 定义函数product_fg
  12. def product_fg(x):
  13.     return f(x) * g(x)

  14. # 获取用户输入并检查范围
  15. a = mp.mpf(input("Please enter the lower limit of integration (0.0001 < a < 10000): "))
  16. b = mp.mpf(input("Please enter the upper limit of integration (0.0001 < b < 10000): "))

  17. if not (0.0001 < a < 10000 and 0.0001 < b < 10000):
  18.     print("Error: The limits must be in the range (0.0001, 10000).")
  19. else:
  20.     # 使用mpmath的quad函数进行积分
  21.     result = quad(product_fg, [a, b], method='tanh-sinh', epsabs=1e-15, epsrel=1e-15)
  22.    
  23.     # 打印结果
  24.     print(f"The result of integration is: {nstr(result, 10)}")
复制代码

主要修正点:

修正quad函数的返回值:quad函数返回的是单个值,所以不需要解包为integral, error。
增加输入范围检查:确保输入的上下限在规定范围内。
使用nstr函数打印结果:nstr函数可以格式化高精度数字以便于阅读。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-19 21:02

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表