Is there an easily available implementation of erf() for Python?

后端 未结 8 2038
日久生厌
日久生厌 2020-12-24 04:54

I can implement the error function, erf, myself, but I\'d prefer not to. Is there a python package with no external dependencies that contains an implementation of this func

8条回答
  •  梦谈多话
    2020-12-24 05:16

    I recommend SciPy for numerical functions in Python, but if you want something with no dependencies, here is a function with an error error is less than 1.5 * 10-7 for all inputs.

    def erf(x):
        # save the sign of x
        sign = 1 if x >= 0 else -1
        x = abs(x)
    
        # constants
        a1 =  0.254829592
        a2 = -0.284496736
        a3 =  1.421413741
        a4 = -1.453152027
        a5 =  1.061405429
        p  =  0.3275911
    
        # A&S formula 7.1.26
        t = 1.0/(1.0 + p*x)
        y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*math.exp(-x*x)
        return sign*y # erf(-x) = -erf(x)
    

    The algorithm comes from Handbook of Mathematical Functions, formula 7.1.26.

提交回复
热议问题