I was implementing an algorithm to calculate natural logs in C.
double taylor_ln(int z) {
double sum = 0.0;
double tmp = 1.0;
int i = 1;
whi
Don't use exact equality operations when dealing with floating point numbers. Although your number may look like 0
, it likely to be something like 0.00000000000000000000001
.
You'll see this if you use %.50f
instead of %f
in your format strings. The latter uses a sensible default for decimal places (6 in your case) but the former explicitly states you want a lot.
For safety, use a delta to check if it's close enough, such as:
if (fabs (val) < 0.0001) {
// close enough.
}
Obviously, the delta depends entirely on your needs. If you're talking money, 10-5 may be plenty. If you're a physicist, you should probably choose a smaller value.
Of course, if you're a mathematician, no inaccuracy is small enough :-)