Anonymous user
Real constants and functions: Difference between revisions
→sqrt (optimized): added/changed comments and whitespace.
(Added Axe) |
(→sqrt (optimized): added/changed comments and whitespace.) |
||
Line 1,573:
===sqrt (optimized)===
A [principal] square root (SQRT) function for REXX (with arbitrary precision):
<lang rexx>/*──────────────────────────────────SQRT
sqrt: procedure; parse
if \datatype(x,'N') then return '[n/a]' /*
i=; if x<0 then do; x=-x; i='i'; end /*handle complex numbers if X is < 0.*/
a=arg(j) /*extract the argument specified*/▼
d=digits()
m.=9
h=d+6
numeric digits 9
if fuzz()\==0 then numeric fuzz 0 /*just in case invoker has a FUZZ set.*/
g=(g * .5) || 'e' || (_ % 2) /*1st guesstimate for the square root. */
/* g= g * .5 'e' (_ % 2) */ /*a shorter & concise version of above.*/
▲if \datatype(x,'N') then return '[n/a]' /*not numberic? not applicable*/
g=(g+x/g) *
end /*k*/ /* [↑] * .5 is
/*
numeric digits d /* [↓] make answer complex if X <
<lang rexx> ╔════════════════════════════════════════════════════════════════════╗
╔═╝ __
║
║
▲return (g/1)left('i',ox<0) /*normalize, add possible suffix.*/</lang>
┌─┘ √ └─┐▼
▲│ While the above REXX code seems like it's doing a lot of extra work, │
▲│ it saves a substantial amount of processing time when the precision │
▲│ (DIGITs) is a lot greater than the default (which is nine digits). │
║ Each iteration of K (approximately) doubles the number of digits, ║
▲│ │
║ but takes almost four times longer to compute (actually, around 3.8). ║
▲│ Indeed, when computing square roots in the hundreds (even thousands) │
║ ║
▲│ of digits, this technique reduces the amount of CPU processing time │
║ The REXX code could be streamlined (pruned) by removing the ║
▲│ by keeping the length of the computations to a minimum (due to a large │
║ The NUMERIC FUZZ 0 statement can be removed if it is known ║
▲│ precision), while the accuracy at the beginning isn't important for │
║ that it is already set to zero. (which is the default). ║
▲│ calculating the (first) guesstimate (the running square root guess). │
║ Also, the NUMERIC FORM statement can be removed if it is known ║
║ that the form is SCIENTIFIC (which is the default). ║
║ __ ║
╚════════════════════════════════════════════════════════════════════╝</lang>
===sqrt (simple)===
|