Coding Techniques
Floating Point Issues · Study material
Kahan (compensated) summation
Adding many small numbers to a large running total loses their low bits. Kahan summation keeps the lost part in a correction variable and feeds it back in. Here a million additions of 0.1f drift by almost 1% naively and stay exact with Kahan.
#include <stdio.h>
int main(void) {
float naive = 0.0f, sum = 0.0f, c = 0.0f;
for (int i = 0; i < 1000000; i++) {
naive += 0.1f;
float y = 0.1f - c; /* Kahan: add back what was lost last time */
float t = sum + y;
c = (t - sum) - y; /* the part of y that did not make it into t */
sum = t;
}
printf("naive %.2f\nkahan %.2f\n", naive, sum);
return 0;
}
naive 100958.34 kahan 100000.00
Compile without -ffast-math: that option lets the compiler "simplify" the correction away.
Store money as integers
Ten additions of 0.10 do not make exactly 1.0 in binary. Keep amounts as whole paise or cents and convert only for display.
#include <stdio.h>
int main(void) {
double total = 0.0;
long cents = 0;
for (int i = 0; i < 10; i++) {
total += 0.10; /* ten coins of 10 paise, in rupees */
cents += 10; /* the same, in whole paise */
}
printf("double: %.17g (== 1.0? %s)\n", total, total == 1.0 ? "yes" : "no");
printf("integer: %ld.%02ld\n", cents / 100, cents % 100);
return 0;
}
double: 0.99999999999999989 (== 1.0? no) integer: 1.00
Avoid subtracting nearly equal numbers
When two close numbers are subtracted, their matching leading digits cancel and only the rounding noise remains ("catastrophic cancellation"). Rewrite the formula: 1 − cos x equals 2 sin²(x/2), which has no subtraction.
#include <math.h>
#include <stdio.h>
int main(void) {
double x = 1e-8;
printf("%.3e %.3e\n", 1 - cos(x), 2 * pow(sin(x / 2), 2)); /* same maths, different accuracy */
return 0;
}
0.000e+00 5.000e-17
Printing and reading floating-point values
| Task | Code |
|---|---|
| Fixed decimals | printf("%.2f", x) |
| Scientific | printf("%.3e", x) |
| Shortest sensible form | printf("%g", x) |
| Exact round-trip (double) | printf("%.17g", x) |
| Read a double | scanf("%lf", &d) – %f is for float |
| Read a float | scanf("%f", &f) |
In printf, %f works for both float and double (floats are promoted); in scanf the two are different.
Good floating-point habits
- Use
double; write float literals withf. - Compare with a relative tolerance, not
==. - Loop with integer counters and compute the real value from them.
- Check for
isnan()/isinf()where input can be bad. - Divide as double when you want a fraction:
sum / (double) n. - Use
fabs()(notabs()) for doubles. - Keep money in integers.