Python 绘制受约束的方程

Python 绘制受约束的方程,python,matplotlib,Python,Matplotlib,到目前为止,我所拥有的: import numpy as np import matplotlib.pyplot asplt import math def graph (formula): x = np.arrange(-4,4,0.1) y = formula(x) plt.plot(x,y) plt.show() def my_formula(x): return ((n**(n-.5))/(math.factorial(n-1)))*((1+x/(math.sqrt(n)))**(n

到目前为止,我所拥有的:

import numpy as np
import matplotlib.pyplot asplt
import math

def graph (formula):
x = np.arrange(-4,4,0.1)
y = formula(x)
plt.plot(x,y)
plt.show()

def my_formula(x):
return ((n**(n-.5))/(math.factorial(n-1)))*((1+x/(math.sqrt(n)))**(n-1))*
  (math.e**(-n*(1+x/(math.sqrt(n)))))
n=1

graph(my_formula)
我搞不懂的是如何将x>-sqrtn约束包含到等式中。任何帮助都将不胜感激

-这是针对一个甚至与编程无关的类的,但我们无论如何都必须做这类事情,所以我真的不太擅长它

x>sqrtn约束限制了x值的范围,当您创建x数组时,您可以很容易地做到这一点

下面是一种实现此目的的方法,请查看带有max的行和后续行,但我还将图形的xlim设置为-4到4范围,以便比较不同的n值:

import numpy as np
import matplotlib.pyplot as plt
from math import factorial, sqrt

def graph(formula, n):
    xmin = max(-sqrt(n), -4) # set the lower x limit for the calculation
    x = np.arange(xmin,4,0.1)
    y = formula(x, n)
    plt.plot(x,y)
    plt.xlim(-4, 4)  # set the graph limits to the full range
    plt.show()

def my_formula(x, n):
    z = 1 + x/sqrt(n)
    a = n**(n-.5)/factorial(n-1)
    b = z**(n-1)
    c = np.exp(-n*z)
    return  a*b*c

n = 4
graph(my_formula, n)
下图中n=4,因此xmin=-2。

此外,这里我也重写了一些代码,尽管这些代码主要是为了清晰。首先,我把n作为一个变量传入,因为多个图都在改变n,如果你想把n当作一个常数,把它直接放在导入之后,这样人们就可以找到它。其次,我将数学函数导入到全局名称空间中,因为在没有名称空间的所有权重的情况下,用代码编写的数学方程足够复杂。第三,我把方程中的三个项分解成一小块一小块的。总的来说,可读性很重要