【问题标题】:How to plot this integral function with infinity boundary?如何绘制具有无限边界的积分函数?
【发布时间】:2019-10-25 02:01:57
【问题描述】:

我正在尝试绘制 Marcum 函数,它是边界中高斯函数的积分。

这是函数:

<a href="https://www.codecogs.com/eqnedit.php?latex=Q(y)=\int_{y}^{\infty}\frac{1}{2\pi}\exp(-\frac{x^2}{2})~dx" target="_blank"><img src="https://latex.codecogs.com/gif.latex?Q(y)=\int_{y}^{\infty}\frac{1}{2\pi}\exp(-\frac{x^2}{2})~dx" title="Q(y)=\int_{y}^{\infty}\frac{1}{2\pi}\exp(-\frac{x^2}{2})~dx" /></a>

y 是用户必须输入的浮点值。我已经编写了代码来以期望的值计算这个函数。但是,我要绘制的是这样的:

!https://ibb.co/SRMsfY3

这里是计算Q(y)值的代码:

from scipy.integrate import quad
import scipy, numpy, math
from scipy import integrate


def integrand(x):
   Q_y = (1/(math.sqrt(2*math.pi)))*math.exp((-x**2)/2)
   return Q_y


y = input('y=')
ans, err = quad(integrand, float(y), math.inf)
print(ans)

我尝试使用以下代码绘制它:

x_data=np.arange(-20,20,0.1)    
z_data=np.arange(float(y),1000,1)

    ans, err = quad(integrand, float(y), math.inf)
    print(ans)

    for item in x_data:
        z_data[i]=integrand(x_data[i])[0]
        i+=1

    fig = plt.figure(1, figsize=(4,4))
    plt.plot(x_data,z_data,color= 'blue',linestyle='--', label=label1)

返回以下错误:

 File "C:/Users/m.rafiee/.spyder-py3/temp.py", line 59, in <module>
    z_data[i]=integrand(x_data[i])[0]

IndexError: index 400 is out of bounds for axis 0 with size 400

我也不知道如何在绘图中添加图中所示的那些注释和散列区域。

非常感谢您提前提供的任何帮助。

【问题讨论】:

  • 提供定义了所有变量的可运行代码。 x_data 是什么?定义人们运行您的代码所需的一切。由于您似乎是 Stack Overflow 的新手,请阅读How do I ask a good question?
  • 感谢您的回复。我添加了 x_data
  • i 未在您在此处显示的代码中定义。但是错误告诉你i 是 400,这对于一个有 400 个值的数组来说太多了(因为第 400 个值的索引为 399)。
  • @Majid : 你需要先自己知道,y 的输入值应该是什么。那么你需要确保当你打印len(x_data)和len(z_data)时,你得到的数字是一样的

标签: python numpy matplotlib math scipy


【解决方案1】:

矢量化你的函数和绘图:

from scipy.integrate import quad
import scipy as sc, numpy as np, math
from scipy import integrate
import matplotlib.pyplot as plt

def integrand(x):
   Q_y = (1/(math.sqrt(2*math.pi)))*math.exp((-x**2)/2)
   return Q_y

func = np.vectorize(integrand)

x = np.arange(-3, 3, 0.1)

fig = plt.figure()
ax = plt.gca()

y = input('y=')

y = float(y)

result = integrand(y)

x_user = np.arange(y, 3, 0.1)

ax.axvline(y, color='green', lw=2, alpha=0.5)

ax.fill_between(x_user, func(x_user), facecolor="none", hatch="/", edgecolor="red")

ax.annotate('Q({0})={1}'.format(y, round(result, 2)), xy=(0, result), xytext=(0, result))

ax.plot(x, func(x))

【讨论】:

  • 谢谢。有效。在我的问题的第二部分,请您也帮我解答一下。如何根据用户输入的 y 值向该图中添加阴影和标记?瞬间,用户输入 2,我希望图表在 x 轴上的数字 2 上显示一条垂直线,并使所有右侧区域阴影。
  • 请看我更新的答案。它与您的示例图像不完全相同,但我认为您会明白它背后的想法。
  • 非常感谢。这与我的预期非常相似。非常感谢。我必须减小线条大小,移动注释并使阴影区域更大一些。
猜你喜欢
  • 1970-01-01
  • 2020-07-31
  • 2021-02-21
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 2015-06-19
  • 2011-04-10
相关资源
最近更新 更多