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
I know that you can do cube roots using powers to the third, but I thought the procedure I posted would of interest to some people (e.g. the basis of a high-precision cube root function or whatever).
Just joking with you, I'm sure your routine will be of use to someone.
With a couple of tweaks it probably would be more useful than the pow() one as that is not very accurate, using doubles and a lower error tolerance would probably work.
Probably about time that PureBasic got itself a scientific maths dll built in.
Thanks for sharing. This routine with Newton-Rapson iteration is much faster and more precise than the general pow(), that can be useful. You can rewrite this function very easy to calculate the square root.
I just doubt if giving an answer for a negative value makes sense - shouldn't it be better to return NaN or NotDefined in that case?
joske wrote:Thanks for sharing. This routine with Newton-Rapson iteration is much faster and more precise than the general pow(), that can be useful. You can rewrite this function very easy to calculate the square root.
I just doubt if giving an answer for a negative value makes sense - shouldn't it be better to return NaN or NotDefined in that case?
Glad you like it.
As Derek points out a cube root of a negative number is perfectly feasible. You only run into problems when trying to get the square root of negative numbers.