Calculating the cube root of a number
Posted: Fri Sep 14, 2007 3:11 pm
Here is some code that I converted from C to calculate cube roots:
Kind regards,
Francis.
Code: Select all
Procedure.f CubeRoot(num.f)
; This procedure is based on code by John T. Hannon Jr
; published in EDN January 15, 1998
;
; Article link: http://www.edn.com/archives/1998/011598/02di.pdf
error.f = 0.00001 ; SET UP MAXIMUM ERROR
root.f = 2.0 ; SET STARTING VALUE
negflag = 0
count = 0
If num < 0 ; IF NUMBER IS NEGATIVE
num = -num ; CHANGE TO POSITIVE &
negflag = 1 ; SET NEG. NUMBER FLAG
EndIf
While (Abs(root * root * root - num)) >= error
root = (num / (root * root) + root) / 2
count + 1
If count > 25 ; IF NO MINIMUM ERROR AFTER 25
Break ; ITERATIONS, EXIT THE FUNCTION
EndIf ; THIS COULD BE LARGER FOR VERY LARGE NUMBERS
Wend
If negflag = 1 ; IF ORIGINAL NUMBER WAS NEGATIVE
root = -root ; SET ROOT TO NEGATIVE NUMBER
EndIf
ProcedureReturn root
EndProcedure
Francis.