How to extract the root in Caché properly
Hi!
Here is the question in Russian Forum regarding roots extracting.
In Caché ObjectScript we use exponentiation operator (**) to raise an exponent to power. F.e. let's raise 3 to power of 3:
USER> write 3**3 27
And we use the same operator to extract the root.
USER> write 27**(1/3) 2.999999999999999963
And 2.999999999999999963 is not 3, obviously.
How to extract roots properly in Caché ObjectScript?
Comments
If I thought the root might be an integer, I guess I would just check:
USER>s n=27,root=n**(1/3),int=$fn(root,"",0) w $s(int**3=n:int,1:root)
3
I was also going to suggest trying logarithms, but someone already suggested that on sql.ru:
USER>w 10**($zlog(27)/3)
2.99999999999999997
USER>w $zexp($zln(27)/3)
2.999999999999999998
This is not fair, Jonathan, you speak Russian!![]()
Thank you, Jon!
Although your example is about integers, you know that any numerical algorithm that deals with roots and logarithms will have to work with floating point numbers. And when dealing with floating point numbers you have to accept that they are not exact representation of real numbers, so you are expected to work within some precision.
If you limit your precision to, say, 8 decimal places, you can get pretty good approximations.
USER>Set n=27,root=n**(1/3) USER>Write $FN(root,"",8) 3.00000000 USER>Write +$FN(root,"",8) 3
Good option. Thanks, Jose!