VBA在excel里面编程的时候,出现了 “运行时错误6” ,溢出,恳请 大神们赐教

是这样的,一个题目,让自己模拟出标准正态分布的分布函数。
也就是模拟出这个 excel里面本身自带的函数: = Norm.s.dist(z,1)
要求自己在VBA里面编写code写一个function来实现这个算法。
我自己做了这个算法,用泰勒公式来计算 error function这个积分的,
但是到了一定程度,比如6个sigma开外,我的函数的结果就跟excel的norm.s.dist(z,1)
的结果有一些误差了,5个sigma之内的误差,在E-10以内。
我的代码是这样的,结果,我算z=8的时候就出现了 ”运行时错误6“,溢出

Option ExplicitOption Base 1
'L.D. I design this function to calculate the CDF of corresponding x
'L.D. I mainly use the Talor's Theorem to calculate the error function
'L.D. which is a part of the integral CDF of normal distribution

Function LiweiNormDist(x As Double) As Double
'so u = F(x) = F(0) + F^(-1)(0)*x + (F^(-2)(0)/2!)*x^2 + _ ' (F^(-3)(0)/3!)*x^3 + ...+ (F^(-n)(0)/n!)*x^n
'and here,as Norm.s.dist(0,1) = 0.5, so F(0) = 0.5,
'and in my formula above, F^(-1)(0) means the first derivative of
'F(x) at x = 0, and F^(-2)(0),F^(-n)(0) can be interpreted in the
'same way

Dim n As Integer, sum As Double, f() As Double, i As Integer
n = 0
sum = 0.5
ReDim f(1)
f(1) = x

Do
n = n + 1
ReDim Preserve f(n + 1)
f(n + 1) = -1 * f(n) * (x ^ 2) * (2 * n - 1) / ((2 * n + 1) * (2 * n))
Loop Until Abs(f(n + 1)) < 10 ^ (-18) And f(n + 1) > 0

For i = 1 To n + 1
sum = sum + f(i) * 1 / Sqr(2 * WorksheetFunction.Pi())
Next i

LiweiNormDist = sum

End FunctionSub mytest()
Dim t As Double t = InputBox("input your number: ")
MsgBox "it's gonna be " & LiweiNormDist(t)

End Sub

我想让误差尽可能地小一些,E-15就可以了。

第1个回答  2012-10-02
Dim n As Integer, sum As Double, f() As Double, i As Integer

→ as开始以及后面的全去掉会有用吗?
Dim n , sum , f() , i
第2个回答  2012-10-02
10 ^ (-18)位数太长了,造成内存溢出。一般EXCEL支持不了太长的位数的。
第3个回答  2012-10-02
问题出在 f(n + 1) = -1 * f(n) * (x ^ 2) * (2 * n - 1) / ((2 * n + 1) * (2 * n)) 语句的分母((2 * n + 1) * (2 * n)) 上,当n>90后,分母值大于整型最大值32767,所以溢出。因为计算中间值是按所含变量的数据类型存贮。
解决的办法有二:一是将n定义为长整型;二是将分母改为两个:即将……/ ((2 * n + 1) * (2 * n)) 改为 …… / (2 * n + 1) / (2 * n)本回答被提问者采纳
相似回答