RosettaCodeData/Task/Nth-root/XPL0/nth-root.xpl0

25 lines
610 B
Text
Raw Permalink Normal View History

2023-07-01 11:58:00 -04:00
include c:\cxpl\stdlib;
2025-02-27 18:35:13 -05:00
func real NRoot(A, N, Prec); \Return the Nth root of A with precision Prec
real A;
int N;
real Prec;
real X, X0, Y, NF;
2023-07-01 11:58:00 -04:00
int I;
2025-02-27 18:35:13 -05:00
[NF:= float(N);
X:= 1.0; \initial guess
2023-07-01 11:58:00 -04:00
repeat X0:= X;
Y:= 1.0;
2025-02-27 18:35:13 -05:00
for I:= 1 to N-1 do Y:= Y*X0;
X:= ((NF-1.0)*X0 + A/Y) / NF;
until abs(X-X0) < Prec; \(until X=X0 doesn't always work)
2023-07-01 11:58:00 -04:00
return X;
];
[Format(5, 15);
2025-02-27 18:35:13 -05:00
RlOut(0, NRoot( 2., 2, 1.0E-15)); CrLf(0);
2023-07-01 11:58:00 -04:00
RlOut(0, Power( 2., 0.5)); CrLf(0); \for comparison
2025-02-27 18:35:13 -05:00
RlOut(0, NRoot(27., 3, 1.0E-15)); CrLf(0);
RlOut(0, NRoot(1024., 10, 1.0E-15)); CrLf(0);
2023-07-01 11:58:00 -04:00
]