简体   繁体   中英

specifying numbers bigger than long double in cython

I have written a function in cython that uses exp function from math.h library of c . Since the input of the exponential function is x=222442.837696 value and the function is supposed to return exp(-x) ,it just returns 0.0 . I have defined the input values of the math library as following:

cdef extern from "math.h":
    long double exp(double) nogil
    double log(double) nogil
    double atanh(double) nogil
    double sqrt(double) 
    double atan(double) nogil
    double atan2(double, double) 
    double sin(double x) 
    double cos(double x) 
    double fabs(double x)
    double pow(double,double) 

The function which is part of a bigger class is

def MassFunction(self, z, mass):
    #Halo mass function based on Evrard et al. 2002
    cdef double a= 0.281
    cdef double b= 0.0123
    cdef double sigma_f=0.578
    cdef double log_sigma=-log(sigma_f)+a*log(mass)+b*log(mass)*log(mass)
    cdef double alpha= a+2*b*log(mass)
    return (0.315*self.rho_m(z)/mass)*alpha*exp(-1*pow(fabs(log_sigma+0.61),3.8))*self.comoving_volume(z)

How could I avoid geting zero value for the exponential function?

You won't be able to avoid getting a 0.0 for exp(-2.2e5) for 64 bit (or even 128 bit) floats. What сan be done here is,

  • Use a library for arbitrary precision arithmetics such as GMP, but you will probably lose in performance in this case.
  • Rewrite your final expression by hand to calculate the logarithm of the mass, and then apply the exponential function. That will solve your problem, assuming the result of the MassFunction is within a reasonable range (eg between 1e-99 and 1e99 ).

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