误差函数的数值实现

原创
09/06 09:49
阅读数 62

最近程序里需要计算高斯概率分布的积分,找到一个实现。用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)))

 

计算结果如下:

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部