简体   繁体   中英

Gamma function plot in Python

So I'd like to plot simple gamma function, but I have some problems. My code is:

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

I tried importing the gamma function from math, and from scipy.special but I get the following error:

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

How to do it? This should be easy, but I seem to fail :(

One of the modules (pylab, I think) is shadowing the gamma function by the gamma random variable function. This works, but I had to turn off the call to legend (I'm not sure why, yet).

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

Try this in a Sage notebook:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM