誤差函數的數值實現

最近程序裏需要計算高斯概率分佈的積分,找到一個實現。用python測試了一下效果還行,把結果記錄下來方便自己查看。

 

# -*- coding: utf-8 -*-

import math
import random

def erf(x):
    result = 0
    index = 0
    while (x / math.pow(10, index) > 1e-3):   # 設置計算精度
        index += 1
    maxIndex = math.pow(10, index)
    deltaX = x/maxIndex
    for i in range(int(maxIndex)+1):
        if (i > 0 and i < maxIndex):
            result += 2*math.exp(-math.pow(deltaX*i, 2))
            continue
        elif (i == maxIndex):
            result += math.exp(-math.pow(deltaX*i, 2))
            continue
        elif (i == 0):
            result += math.exp(-math.pow(deltaX*i, 2))
            continue
        
    return result*deltaX/math.pow(math.pi, 0.5)


for i in range(10):
    x = random.uniform(0,2)
    print("x: ", x)
    print("erf(x) = ", math.erf(x))
    print("my erf(x) = ", erf(x))
    print()

# calc probability erf( (x-\mu)/(sqrt(2)*sigma) )
# while \mu = 0, sigma = 1
print("1sigma: ", erf(1/math.sqrt(2)))
print("2sigma: ", erf(math.sqrt(2)))
print("3sigma: ", erf(3/math.sqrt(2)))

 

計算結果如下:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章