This simple example illustrates how the Script element can be used to carry out an iterative calculation. It can be found in a file (Script.gsm) that is located in the General Examples folder of your GoldSim directory (accessed by selecting File | Open Example... from the main menu). The example uses Newton’s method to calculate the square root of 101. While you’re certainly not likely to need to calculate the square root of 101 by Newton’s method, the model does provide a nice example of how to iterate within a script.
Newton’s method is a successive approximation method for finding real roots of differentiable functions.
For a function f(X), which in this case represents the error in the approximation, which we wish to go to zero, the formula for Newton’s method is:
Where f ’ (Xn) is the first derivative with respect to X, and Xn is the nth approximation of the root (X0 is an initial guess for the root). Therefore, in our example of finding the square root of 101:
f(X) = X2 – 101; and
f ’(X) = 2X.
The script used for this simple example to solve for the square root of the variable Val is shown below:
The script starts out with Variable Definition statements in lines 1 and 2. Note that when script variables are referenced on the right side of equations (e.g., in line 4), a ~ symbol is required. This is because script variables are locally available properties. In line 1, the script references an element outside this Script element called Val (a constant whose square root is being sought, 101). Note that referencing another element’s output does not require the ~ symbol.
After the Variable Definition statements, a FOR loop is defined. The FOR loop starting in line 3 shows that it creates a loop variable (named “I”) that is initially 1 and is incremented by 1 on each iteration, continuing while the expression “I<=MaxIterat” is true. Hence, the FOR loop executes the statements it contains until it is broken by a BREAK statement, or the loop count reaches the specified maximum number of iterations possible. In each FOR loop iteration, two more Variable Definition statements (with expressions as the assignments) compute the values for the function (F) and the derivative (FPrime). A Variable Assignment statement (line 13) then generates a new approximation of the square root at the bottom of the loop.
The IF statement block beginning at line 7 tests the approximation error in the current estimate of the square root. If it is sufficiently small, a BREAK statement is executed to terminate the FOR loop.
If the approximation error remains high and the maximum number of iterations is reached, a LOG statement (line 10) is written to the Run Log noting that the script failed to converge. Line 6 is another LOG statement reporting the progress of the successive approximations for each iteration of the FOR loop.
Learn more about:
Defining Local Script Variables