Python中的伽马函数图绘制
我想画一个简单的伽马函数,但是遇到了一些问题。我的代码是:
#!/usr/bin/env python
# -*- coding: cp1250 -*-
#import math
from scipy.special import *
#from scitools.std import *
from pylab import *
def f1(x):
return gamma(x)
x = linspace(-6, 6, 512)
y1 = f1(x)
# Matlab-style syntax:
plot(x, y1)
xlabel('x')
ylabel('y')
legend(r'$\Gamma(x)$')
grid(True)
show()
我尝试从math和scipy.special导入伽马函数,但出现了以下错误:
追踪记录(最近的调用在最前面): 文件 "D:/faxstuff/3.godina/kvantna/plotgamma.py",第13行,y1 = f1(x) 文件 "D:/faxstuff/3.godina/kvantna/plotgamma.py",第9行,return gamma(x) 文件 "mtrand.pyx",第1599行,在mtrand.RandomState.gamma (numpy\random\mtrand\mtrand.c:8389) 值错误:形状 <= 0
我该怎么做呢?这应该很简单,但我似乎做错了 :(
2 个回答
2
在Sage笔记本中试试这个:
# Simple example demonstrating how to interact with matplotlib directly.
# Comment plt.clf() to get the plots overlay in each update.
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
@interact
def plot_gamma(a=(1,(1,10)), loc=(0,(0,10)), scale=(1,(1,10))):
rv = stats.gamma(a, loc, scale)
x = np.linspace(-1,20,1000)
plt.plot(x,rv.pdf(x))
plt.grid(True)
plt.savefig('plt.png')
plt.clf()
3
其中一个模块(我想是pylab)把伽马函数给覆盖了,变成了伽马随机变量函数。这样做是可以的,但我不得不关闭图例的调用(我还不太明白为什么)。
from scipy.special import gamma as Gamma
#from scitools.std import *
from pylab import *
def f1(x):
return Gamma(x)
x = linspace(-6, 6, 512)
y1 = f1(x)
gca().set_autoscale_on(False)
# Matlab-style syntax:
plot(x, y1)
xlabel('x')
ylabel('y')
# legend(r'$\Gamma(x)$')
axis([-6, 6, -100, 100])
grid(True)
show()