- Joined
- 8/10/05
- Messages
- 144
- Points
- 28
Don't know how many of you got the Bermuda Option question correctly on 9821 final, but I know I got it wrong. I finally figured out what I did wrong and matched Andy's & Alain's numbers. I'm using a Mac (a PowerBook), with the PowerPC chip that is, and it seems that the precision of the 'double' primitive is a bit different between PowerPC & Intel chips. However, the 'long double' primitive (which has higher precision than a 'double') seems to have the same precision. Here is some code to illustrate this:
Output from my PowerBook:
Output from my PC (Pentium 4, Windows XP):
The code above sums the fraction 5/100 in a loop for 100 times using both primitive types: 'double' and 'long double'. The 'long double' gives much better result, while the 'double' gives slightly different numbers between PowerPC & Intel chips, a subtle difference but it can drive one nut!
I'm going to start using 'long double' more often now. I know a few of us are using a Mac so hopefully you don't have to spend hours debugging your code.
Code:
double num = 5.0;
long double long_num = 5.0;
double denom = 100.0;
long double long_denom = 100.0;
double fraction = num/denom;
long double long_fraction = long_num/long_denom;
double total = 0.0;
long double long_total = 0.0;
for (int i=0; i < denom; i++)
{
total += fraction;
long_total += long_fraction;
}
cout.setf(ios::fixed, ios::floatfield);
cout.precision(18);
cout << " num=" << num << endl;
cout << " total=" << total << endl;
cout << "long_total=" << long_total << endl;
Code:
[Session started at 2007-01-03 23:42:45 -0500.]
num=5.000000000000000000
total=4.999999999999990230
long_total=5.000000000000000000
Final has exited with status 0.
Code:
$ ./MTH9821.exe
num=5.000000000000000000
total=4.999999999999990200
long_total=5.000000000000000000
Press any key to continue . . .
I'm going to start using 'long double' more often now. I know a few of us are using a Mac so hopefully you don't have to spend hours debugging your code.