How to print a double in C with absolute or relative error 10⁻⁶

2.6k Views Asked by At

I want to print a decimal number with error at most 10-6. What does error at most 10-6 mean? E.g.: 10.35652383, Which of the following two options is correct?

1)10.356523 or 2)10.356524

As printf("%.6lf") prints with the decimal rounded off to 6 decimal places 10.356524 will be printed.

2

There are 2 best solutions below

0
On

To print to the nearest 0.000001, use "%.6f"

double x = 10.35652383;
printf("%.6f\n", x);
// or
printf("%.*f\n", 6, x);
// or drop .6, .6 is the default
printf("%f\n", x);

10.356524

To print to an approximate 0.000001*x, use "%.6e"

printf("%.6e\n", x);
// or
printf("%.*e\n", 6, x);
// or drop .6, .6 is the default
printf("%e\n", x);

1.035652e+01

Alternatively for relative precision: code could use the below when fabs(x) < 1000000. It is unclear what is wanted when x is larger.

printf("%.*f\n", 6 - (int) log10((fabs(x)), x);

10.35652

The use of l as in %lf work the same as without it: %f for printf().

0
On

Let's calculate both absolute and relative errors:

x = 10.35652383
x1 = 10.356523
x2 = 10.356524

print "absolute error 1: {0}".format(abs(x1 - x))
print "absolute error 2: {0}".format(abs(x2 - x))

print "relative error 1: {0}".format(abs((x1 - x)/x))
print "relative error 2: {0}".format(abs((x2 - x)/x))

It gives:

absolute error 1: 8.30000001173e-07
absolute error 2: 1.69999999855e-07
relative error 1: 8.01427211289e-08
relative error 2: 1.64147741699e-08

So both absolute and relative errors are below 10e-6, i.e. below 0.000001, but the second value is closer.