VBA EXCEL : Why do I keep getting an error for yfunc ? Option Explicit Const XTO
ID: 3795312 • Letter: V
Question
VBA EXCEL : Why do I keep getting an error for yfunc ?
Option Explicit
Const XTOL = 0.0001
Const YTOL = 0.0001
Const RGAS = 8314.33
Function NRsolve(xguess As Double, MAXITER As Integer) As Double
Dim iter As Integer
Dim xnew As Double
Dim xold As Double
Dim y As Double
Dim dydx As Double
Dim status As Integer
'Copy initial estimate into xold
'-------------------------------
xold = xguess
'For loop going from 1 to maximum allowable # of iterations
'----------------------------------------------------------
For iter = 1 To MAXITER
y = yfunc(xold) 'Calculate current value of y with function <yfunc>
If Abs(y) < YTOL Then Exit For 'Test if current value of y is less than tolerance
dydx = fprime(xold) 'Calculate current value of dydx with function <fprime>
xnew = xold - y / dydx 'Update xnew ... this is the NR algorithm
If (Abs(xnew - xold) < XTOL) Then Exit For 'Convergence test #2: Is x changing enough?
xold = xnew
Next
NRsolve = xnew
status = MsgBox(iter, vbOKOnly, "# of iterations")
End Function
Function yfunc(x As Double, T As Double, P As Double, A As Double, B As Double) As Double
Dim status As Integer
Dim A As Double
Dim T As Double
Dim B As Double
Dim P As Double
Dim alias As String
Call SRK_EOS_Params(alias, T, A, B)
yfunc = x ^ 3 - ((RGAS * T) / P) * x ^ 2 + (1 / P) * (A - B * RGAS * T - P * B ^ 2) * x - ((A * B) / P)
End Function
Function fprime(x As Double)
Call SRK_EOS_Params(alias, T, A, B)
Dim alias As String
Dim A As Double
Dim T As Double
Dim B As Double
Dim P As Double
fprime = 3 * x ^ 2 * (P / (RGAS * T)) ^ 2 - 2 * x * (P / (RT)) + (((A * P) / (RGAS ^ 2 * T ^ 2)) - ((B * P) / (RGAS * T)) - ((B * P) / (RGAS * T)) ^ 2)
fprime = dy / dx
End Function
Explanation / Answer
Your code has several errors.
First error bein with function yfunc.You have clearly declared 5 double variables in it as arguments. However , While calling yfunc, there is only one argument. Because of which you are getting error for Yfunc. Kindly provide necessary arguments.
Secondly you have made duplicate declaration for variable A as double. It is passed as an argument in yfunc & declared it seperately under the yfunc function. This is causing the code to produce errors.
I suggest you use Keyword F8 to debug your code line by line. You shall get some idea as in where your code is getting stuck.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.