Returning to your roots
Or, Calculating ![]()
The root() softcode function uses the standard C sqrt() and (optionally) cbrt() functions (cbrt() isn't common on non-UNIX systems yet due to slow uptake of the 1999 standard) to get accurate square and cube roots. Higher roots are calculated using the equation
. Unfortunately, in the world of IEEE-754 floating point math, this is only an approximation. Because of how Penn does rounding to a specified number of decimal digits (The float_precision config option), this usually doesn't matter with the default setting (6); the number it returns is accurate enough.
With a higher precision (Like 15, which is the most you can reasonably get out of the 64-bit double type), inaccuracy becomes more noticeable (For certain values of noticeable). For example, root(400,4) returns 4.472135954999579. power(4.472135954999579,4) returns 399.999999999999773.
Using an implementation of the algorithm described here, root(400,4) returns 4.47213595499958, and power(4.47213595499958,4) is 400.000000000000057. More accurate (By one place), but you can't get away from the inherent inaccuracy of floating point. Brazil wrote on the topic here. More precise numeric libraries exist; I don't think that Penn is used for numeric code where an extreme degree of precision matters enough to bother using one. Of more use would be changing the double-to-string code to use scientific notation for very large and small numbers (The string-to-double code already understands it.) The revised root() will be in an upcoming patchlevel, though.
Because the algorithm is a iterative one, with each approximation to the root being based on a less-precise approximation (Or guess), you have to figure out when to stop. My implementation stops if a) Two successive approximations are "close enough" based on the current float_precision setting that they will be identical when converted to strings, or after 100 repetitions. The first case will probably always match first; the second is just in for paranoia about what numbers Ashen-Shugar might come up with to throw at it. ;)
- raevnos's blog
- Login or register to post comments

Click 
