0

I want to make Newton-Raphson iteration but stuck on how to incorporate changing Y into the function of interest. For the values of Tpr and Ppr varibles in my code, I expect to have value of Z approx 0.78. My code as below:

Sub Z_Factor()

Dim Z As Double
Dim t As Double
Dim Tpr As Double
Dim Ppr As Double
Dim X1 As Double
Dim X2 As Double
Dim X3 As Double
Dim X4 As Double
Dim Y As Single
Dim Ynext As Single
Dim DensityFunction As Double
Dim DensityFunctionPrime As Double
Dim i As Integer

Tpr = 1.52
Ppr = 2.99
t = 1 / Tpr
X1 = -0.06125 * Ppr * t * Exp(-1.2 * (1 - t) ^ 2)
X2 = 14.76 * t - 9.76 * t ^ 2 + 4.58 * t ^ 3
X3 = 90.7 * t - 242.2 * t ^ 2 + 42.4 * t ^ 3
X4 = 21.8 + 2.82 * t

' starting guess of Y is calculated as: 
Y = 0.0125 * Ppr * t * Exp(-1.2 * (1 - t) ^ 2)

For i = 1 To 100

    DensityFunction = X1 + ((Y + Y ^ 2 + Y ^ 3 + Y ^ 4) / (1 - Y) ^ 3) - X2 * Y ^ 2 + X3 * Y ^ X4

    ' derivative of DensityFunction
    DensityFunctionPrime = ((1 + 4 * Y + 4 * Y ^ 2 - 4 * Y ^ 3 + Y ^ 4) / (1 - Y) ^ 4 - 2 * X2 * Y + X3 * X4 * Y ^ (X4 - 1))

    Ynext = Y - DensityFunction / DensityFunctionPrime

    If Abs(Ynext - Y) <= 0.000000000001 Then
    Z = ((0.06125 * Ppr * t) / Y) * Exp(-1.2 * (1 - t) ^ 2)

    Else
    Y = Ynext
    End If

Next i

End Sub
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Zak
  • 41
  • 1
  • 4
  • 1
    Is this a math problem or a coding problem? What does the code do right now? Wrong output? Error? – urdearboy Oct 03 '18 at 01:52
  • 1
    The code does execute without any error. However, once the 'if' condition is met, the code doesn't stop and continues to iterate. The output is also incorrect. As I mentioned, I expect the output to be approx 0.78. The whole idea is to assume a value of Y. Use it in 'DensityFunction' such that 'DensityFunction' ~ 0. If not, assume another value of Y ('Ynext') and then use 'Ynext' into 'DensityFunction' – Zak Oct 03 '18 at 09:05
  • 1
    *the code doesn't stop and continues to iterate*. To stop the iteration, you can use `Exit For`. Read more about it here: https://stackoverflow.com/a/9415163/9199828 – Foxfire And Burns And Burns Oct 03 '18 at 09:15
  • @FoxfireAndBurnsAndBurns thanks and it works. As for the incorrect output, there was an error in one of the formulas I was using. – Zak Oct 03 '18 at 16:53

0 Answers0