|
From: Szczepan H. <ru...@wp...> - 2005-05-03 11:31:27
|
> Just a suggestion to your algorithm in
> order to not use an "if/else" statement.
<snip>
> for(double i = 3; i < 999999999; i+=2)
> {
> sign *= -1;
> PI += ((numerator/i)*sign);
> }
... and since an assignment expression itself has a value equal to the
value assigned, this may be rewritten as a one-liner without curly
braces:
for(double i = 3; i < 999999999; i+=2)
PI+=((numerator/i)*(sign = -sign));
Note that "sign = -sign" might be more efficient if your compiler
cannot optimize multiplication by -1 to a single FP negate instruction
to avoid full FP multiplication.
Another optimization is to factor out the sign switching altogether.
You could increment the loop by 4 instead of 2 and add two terms in
one iteration:
for(double i = 3; i < 999999999; i+=4)
PI += -numerator/i + numerator/(i+2);
This method reduces the number of loop iterations by two. This is an
additional benefit because each loop iteration involves a conditional
branch, and conditional branches are bad for performance on modern
CPUs.
(Note that the result might be slightly different now because of an
off-by-one issue: you might be adding an extra term in the last
iteration because the "(i+2)" is no longer checked against the loop
exit condition.)
BTW., I didn't know that PI could be calculated like this! From what I
know about harmonic series it must converge painfully slowly, hence
999999999... :)
Regards,
Szczepan Holyszewski
|