2011-04-16 431 views
1

所以我想繪製簡單的伽馬函數,但我有一些問題。我的代碼是: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() 

我試圖從數學進口伽瑪功能,並從scipy.special但我得到以下錯誤:

Traceback (most recent call last): File "D:/faxstuff/3.godina/kvantna/plotgamma.py", line 13, in y1 = f1(x) File "D:/faxstuff/3.godina/kvantna/plotgamma.py", line 9, in f1 return gamma(x) File "mtrand.pyx", line 1599, in mtrand.RandomState.gamma (numpy\random\mtrand\mtrand.c:8389) ValueError: shape <= 0

怎麼辦呢?這應該很容易,但我似乎失敗:(

+0

請後確切的錯誤消息 – 2011-04-16 09:34:54

+0

'回溯(最近最後一次通話): 文件「D:/faxstuff/3.godina/kvantna/plotgamma.py」,第13行,在 y1 = f1(x) 文件「D:/faxstuff/3.godina/kvantna/plotgamma.py」,第9行,在f1中 返回gamma(x) 文件「mtrand.pyx」,行1599,in mtrand.RandomState.gamma(numpy \ random \ mtrand \ mtrand.c:8389) ValueError:shape <= 0' – 2011-04-16 10:30:30

+1

這是不推薦使用'import *'的原因。 – OldGeeksGuide 2016-11-24 00:36:15

回答

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() 
+0

需要將其更改爲:legend([r'$ \ Gamma(x)$']) – 2011-04-16 10:57:15

+0

好極了,現在可以使用。 ^^ – 2011-04-16 11:15:37

+4

這是爲什麼不推薦「來自foo import *」的完美例證。 – DaveP 2011-04-18 07:18:48

2

在聖人筆記本試試這個:。

# 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()