【问题标题】:Hello, I was trying to integrate a hemisphere using scipy dblquad function, and its not working您好,我正在尝试使用 scipy dblquad 函数集成半球,但它不起作用
【发布时间】:2021-12-31 10:37:53
【问题描述】:

我的代码是

import numpy as np
from scipy import integrate
from math import *
import cmath


f = lambda y, x: cmath.sqrt(1 - x**2 - y**2)
hemisphere = integrate.dblquad(f, -1, 1, lambda x: -1, lambda x: 1)

print(hemisphere)

我得到的错误是

TypeError: can't convert complex to float

因为根是负数,所以它包含复数。

我能做些什么让它正常工作吗?

非常感谢。

【问题讨论】:

  • 这个模块可能无法实现如此复杂的集成。我相信通过一些手工计算,可以使用here 描述的技术。

标签: python math scipy


【解决方案1】:

使用math.sqrtnp.sqrt 而不是cmath.sqrtintegrate.dblquad 无法处理复数,即使这些复数的虚部始终为零,从数学上讲,使用复数毫无意义数字在这里。

为避免取负数平方根的潜在问题,您可以:

  • 调整被积函数,使其在感兴趣区域之外为零,或者
  • 调整限制,以便在单位圆盘上而不是在正方形上积分

这是执行前者的代码版本。请注意使用np.maximumnp.sqrt 而不是Python 内置的maxmath.sqrt:这确保f 适用于数组参数以及标量参数,这可能允许dblquad 计算其结果更快。

import numpy as np
from scipy import integrate

f = lambda y, x: np.sqrt(np.maximum(0.0, 1 - x**2 - y**2))
hemisphere = integrate.dblquad(f, -1, 1, lambda x: -1, lambda x: 1)

print(hemisphere)

对我来说,这会产生2/3 π 的预期近似值:

(2.0943951045290796, 1.855738140932317e-08)

这是您的代码版本,它可以调整限制:


import numpy as np
from scipy import integrate

f = lambda y, x: np.sqrt(1 - x**2 - y**2)
hemisphere = integrate.dblquad(f, -1, 1, lambda x: -np.sqrt(1-x*x),
                                         lambda x: np.sqrt(1-x*x))

print(hemisphere)

【讨论】:

  • 非常感谢!你是救生员!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-30
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-28
相关资源
最近更新 更多