pow function does not handle exponents >10
Closed this issue · 2 comments
Issue description
// The following code illustrates the problem..
// defining my own longPow function as a workaround
long longPow ( int val, int rank )
{
long v = 1;
for ( ; rank > 0; rank--)
v *= val;
return v;
}
void setup() {
long v = int(pow(9, 10)); //<------ testing pow
long vl = longPow(9, 10); //<------ testing longPow
print (v + "\n");
print (vl + "\n");
}
// output is:
2147483647 <-- incorrect
3486784401 <-- correct value
// I have timed the two functions, and I get the following result:
int(pow(9,10)): 15700 nsec
longpow(9,10): 4500 nsec
The pow function is incorrect for exponent >10 and also up to 3x slower.
Of course the reason for the performance difference is because 'pow' computes a fractional exponent x^y where 'x' and 'y' may be floating point. Computation of floating point powers is naturally slower. This also explains the error, because exponent >10 results in a value which exceeds the float type size, and casting to long after the fact does not.
My code was acting weirdly and it took some time to trace this issue to the built-in 'pow' function.
URL(s) of affected page(s)
Unknown.
Proposed fix
The best solution would be to provide a built-in longPow function as above which is both faster and correct for integers, and provide a warning to the user when the 'pow' function exceeds its range.
2147483647 is the maximum value for an integer; so you're casting a huge number to an int
, and getting this result. We don't deal with long
anywhere in the API, if you're aware of its existence you're probably better off using Math.pow()
instead of the built-in function.
Hi Ben, thanks for the reply!
A little surprised to see you respond, thanks!
https://processing.org/reference/long.html
I didn't think to use the javascript func but makes sense. My workaround func works too.
Thanks, R
http://ramakarl.com