我正在尝试使用Excel VBA执行集成。如果我需要整合一个负指数(因为x / 0未定义,因此这样的近似值无法估计它),我想知道如何使用近似方法做到这一点
我目前的代码是:
Function Integral(sExp As String, dMin As Double, dMax As Double, lBit As Long)
Dim dU As Double
Dim lU As Long
dU = (dMax - dMin) / lBit
For lU = 1 To lBit
IntegralTemp = IntegralTemp + Evaluate(Replace(sExp, "u", dMin)) * dU + 0.5 * dU * Abs(Evaluate(Replace(sExp, "u", dMin + dU)) - Evaluate(Replace(sExp, "u", dMin)))
dMin = dMin + dU
Next lU
Integral = IntegralTemp
End Function
答案 0 :(得分:0)
答案 1 :(得分:0)
我认为这是function Evaluate
的问题。
我尝试解决这个问题,并设法做到:
看看这个测试功能:
Function EvaluateTest(str As String)
EvaluateTest = Evaluate(str)
EvaluateTest = CStr(EvaluateTest)
End Function
debug.Print EvaluateTest("0^(-0.05)")
显示Error 2007
我认为这除以零 - > 0^(-0.05) for VBA is 0/(0^0.05)
我们可以捕获此错误,并且对于那个案例,接受结果= 0
我创建函数使用来捕获这个1错误并修改了你的功能。试试这段代码:
Function EvaluateCheck(Exp As String)
Dim EvalCheck As Variant
EvalCheck = Evaluate(Exp)
If VarType(EvalCheck) = vbError Then 'evaluate function error
Select Case CInt(EvalCheck)
Case 2007 ' 0/x
'Debug.Print "Evaluate(" & Exp & ") error= " & CStr(EvalCheck); ""
EvaluateCheck = 0
'Case 2015 ' other problems with evaluate (power)
'Debug.Print "Evaluate(" & Exp & ") error= " & CStr(EvalCheck); ""
'try use power function not evaluate
'FindTmp = WorksheetFunction.Find("^", Exp)
'If FindTmp > 0 Then
'number_ = CDbl(Mid(Exp, 1, FindTmp - 1))
'Power_ = Mid(Exp, FindTmp + 1, Len(Exp))
'Power_ = Replace(Power_, ".", ",") '<- i have problems with CDbl function i must replace . to , maybe you dont need this line
'Power_ = Replace(Replace(Power_, "(", vbNullString), ")", vbNullString) ' we dont need parentheses
'PowerDbl = CDbl(Power_)
'EvaluateCheck = WorksheetFunction.power(number_, PowerDbl)
'Else
'Debug.Print "Evaluate(" & Exp & ") error= " & CStr(EvalCheck); " i cant handle that case"
'End If
Case Else
Debug.Print "Evaluate(" & Exp & ") error= " & CStr(EvalCheck); " i cant handle that case"
End Select
Else ' evaluate no error
EvaluateCheck = EvalCheck
End If
End Function
你的职能:
Function Integral(sExp As String, dMin As Double, dMax As Double, lBit As Long)
Dim dU As Double
Dim lU As Long
Dim eval As Long
Dim EvaluateVal1 As Double 'Evaluate(Replace(sExp, "u", dMin))
Dim EvaluateVal2 As Double 'Evaluate(Replace(sExp, "u", dMin + dU))
Dim sExpTmp As String
dU = (dMax - dMin) / lBit
For lU = 1 To lBit
'check evaluate
sExpTmp = Replace(sExp, "u", dMin)
EvaluateVal1 = EvaluateCheck(sExpTmp)
sExpTmp = Replace(sExp, "u", dMin + dU)
EvaluateVal2 = EvaluateCheck(sExpTmp)
IntegralTemp = IntegralTemp + EvaluateVal1 * dU + 0.5 * dU * Abs(EvaluateVal1 - EvaluateVal2)
dMin = dMin + dU
Next lU
Integral = IntegralTemp
End Function
一些结果:
debug.print Integral("u^(-0.05)", 0, 1, 500)
1,05186339856455
debug.print Integral("u^(-0.05)", 0.05, 1, 500)
0,991802803730478
debug.print Integral("u^(-0.05)", 0.05, 1.05, 500)
1,0417624389399