簡體   English   中英

將函數作為參數傳遞給類

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

我有一個函數是由:

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

我想將此函數傳遞給以下類,該類位於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

當我調用類時,我不知道如何將輸入參數x作為輸入參數傳遞給函數p(z)

 from redshift_probability import GeneralRandom
 z_pdf=GeneralRandom()

如果執行以下操作,則會出現錯誤:

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

如何修改?

我認為您想將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)

然后這樣稱呼它:

GeneralRandom(p_func=p)

這樣,如果您提供p_func ,它將以x作為參數調用,但是如果未提供,它將設置為與以前相同的默認值。 無需顯式調用set_pdf ,因為它是在__init__的末尾調用的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM