简体   繁体   English

将函数作为参数传递给类

[英]passing a function as an argument to a class

I have a function is given by : 我有一个函数是由:

import scipy.special
def p(z):
    z0=1./3.;eta=1.0
    value=eta*(z**2)*numpy.exp(-1*(z/z0)**eta)/scipy.special.gamma(3./eta)/z0**3 
    return value

I want to pass this function to the following class which is in the file called redshift_probability.py as an argument p : 我想将此函数传递给以下类,该类位于redshift_probability.py文件中,作为参数p

import pylab
import numpy
import pylab
import numpy

class GeneralRandom:
  """This class enables us to generate random numbers with an arbitrary 
  distribution."""

  def __init__(self, x = pylab.arange(-1.0, 1.0, .01), p = None, Nrl = 1000):
    """Initialize the lookup table (with default values if necessary)
    Inputs:
    x = random number values
    p = probability density profile at that point
    Nrl = number of reverse look up values between 0 and 1"""  
    if p == None:
      p = pylab.exp(-10*x**2.0)
    self.set_pdf(x, p, Nrl)

  def set_pdf(self, x, p, Nrl = 1000):
    """Generate the lookup tables. 
    x is the value of the random variate
    pdf is its probability density
    cdf is the cumulative pdf
    inversecdf is the inverse look up table

    """

    self.x = x
    self.pdf = p/p.sum() #normalize it
    self.cdf = self.pdf.cumsum()
    self.inversecdfbins = Nrl
    self.Nrl = Nrl
    y = pylab.arange(Nrl)/float(Nrl)
    delta = 1.0/Nrl
    self.inversecdf = pylab.zeros(Nrl)    
    self.inversecdf[0] = self.x[0]
    cdf_idx = 0
    for n in xrange(1,self.inversecdfbins):
      while self.cdf[cdf_idx] < y[n] and cdf_idx < Nrl:
        cdf_idx += 1
      self.inversecdf[n] = self.x[cdf_idx-1] + (self.x[cdf_idx] - self.x[cdf_idx-1]) * (y[n] - self.cdf[cdf_idx-1])/(self.cdf[cdf_idx] - self.cdf[cdf_idx-1]) 
      if cdf_idx >= Nrl:
        break
    self.delta_inversecdf = pylab.concatenate((pylab.diff(self.inversecdf), [0]))

  def random(self, N = 1000):
    """Give us N random numbers with the requested distribution"""

    idx_f = numpy.random.uniform(size = N, high = self.Nrl-1)
    idx = pylab.array([idx_f],'i')
    y = self.inversecdf[idx] + (idx_f - idx)*self.delta_inversecdf[idx]

    return y

I don't know how to pass input argument x as an input parameter to function p(z) when I call the class 当我调用类时,我不知道如何将输入参数x作为输入参数传递给函数p(z)

 from redshift_probability import GeneralRandom
 z_pdf=GeneralRandom()

If I do as following I get error: 如果执行以下操作,则会出现错误:

 z_pdf.set_pdf( x=numpy.arange(0, 1.5, .001),p(x),N=1000000)

How do I modify it? 如何修改?

I think you want to change GeneralRandom.__init__ to look like this: 我认为您想将GeneralRandom.__init__更改为如下形式:

  def __init__(self, x = pylab.arange(-1.0, 1.0, .01), p_func=None, Nrl = 1000):
    """Initialize the lookup table (with default values if necessary)
    Inputs:
    x = random number values
    p_func = function to compute probability density profile at that point
    Nrl = number of reverse look up values between 0 and 1"""  
    if p_func is None:
        self.p_val = pylab.exp(-10*x**2.0)
    else:
        self.p_val = p_func(x)

Then call it like this: 然后这样称呼它:

GeneralRandom(p_func=p)

That way, if you provide p_func it will be called with x as an argument, but if it's not provided, it gets set the same default as before. 这样,如果您提供p_func ,它将以x作为参数调用,但是如果未提供,它将设置为与以前相同的默认值。 There's no need to call set_pdf explicitly, because it's called at the end of __init__ . 无需显式调用set_pdf ,因为它是在__init__的末尾调用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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