【问题标题】:Gamma function plot in PythonPython中的伽玛函数图
【发布时间】:2011-04-16 09:33:02
【问题描述】:

所以我想绘制简单的 gamma 函数,但我遇到了一些问题。我的代码是:

#!/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 导入 gamma 函数,但出现以下错误:

回溯(最近一次调用最后):文件“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 行,在 mtrand.RandomState.gamma (numpy\random\mtrand\mtrand.c:8389) ValueError: shape

怎么做?这应该很容易,但我似乎失败了:(

【问题讨论】:

  • 请发布确切的错误信息。
  • Traceback (most recent call last): File "D:/faxstuff/3.godina/kvantna/plotgamma.py", line 13, in <module> 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
  • 这是一个很好的例子说明为什么不推荐import *

标签: python plot scipy matplotlib


【解决方案1】:

其中一个模块(我认为是 pylab)正在通过 gamma 随机变量函数隐藏 gamma 函数。这行得通,但我不得不关闭对图例的调用(我还不确定为什么)。

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

【讨论】:

  • 需要改成:legend([r'$\Gamma(x)$'])
  • 这很好地说明了为什么不推荐使用“from foo import *”。
【解决方案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()

【讨论】:

    猜你喜欢
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 2021-08-12
    • 1970-01-01
    相关资源
    最近更新 更多