0

I'm not sure how floating point are represented in C, and how much of a precision someone could get. In a c source file, I have the macro:

#define NUMBER 123.367

In the main function there are these 2 instructions:

float x = NUMBER;
printf("x is %f\n", x);

When I run it, I get:

x is 123.366997

Which is quite close to 123.367, but it kinda messes the purpose of the program. Is there any way to round up x to the desired value? Or is this a flaw of floating point arithmetic-representation that can't be fixed?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Andrew
  • 84
  • 2
  • 11
  • 123.367 is an infinitely recurring number in binary (like 1/7 in decimal), so it can't be represented exactly. When printing numbers like this, you should specify the number of digits you want to see. For example `printf("x is %.3f\n", x);` – r3mainer Jul 01 '18 at 22:07
  • Use integers if you need a specific precision (such as pennies of a dollar, counting the number of pennies). Not all numbers can be expressed exactly as a binary float (0.1 for example), since it would be an infinite repeating sequence that gets truncated. – e0k Jul 01 '18 at 22:11
  • A good reference is [What Every Programmer Should Know About Floating-Point Arithmetic](http://www.phys.uconn.edu/~rozman/Courses/P2200_15F/downloads/floating-point-guide-2015-10-15.pdf) – David C. Rankin Jul 01 '18 at 22:12
  • You said "kinda messes the purpose of the program", and I kinda know what you mean, but when working with floating point, it's important to be clear on what the purpose of the program truly is. What *is* the significance of that number 123.367? Is its value truly 123.367000000000000, exactly? Or is it a measurement which you're pretty sure (but not exactly sure) of, maybe 123.367 ± 0.0001, or ± 0.001? – Steve Summit Jul 02 '18 at 01:10
  • Once you've defined the proper interpretation of the number, it will be easier to decide an appropriate strategy for representing and manipulating it as a `float` or `double` variable in a C program (including dealing with the fact that, as discussed in these comments and answers, a binary floating-point format can't exactly represent the number 123.367 after all). – Steve Summit Jul 02 '18 at 01:11

1 Answers1

0

You should use a double, not a float.

#include <stdio.h>
#define NUMBER 123.367

int main (void) {
  float f = NUMBER;
  double d = NUMBER;

  printf("f is %f\n", f);
  printf("d is %f\n", d);

  return 0;
}

This will give you:

f is 123.366997
d is 123.367000

'double' uses 53 bits for precision, while a 'float' only uses 24.

Bert
  • 2,134
  • 19
  • 19
  • 4
    While it's true that `double` should usually be preferred over `float`, it still doesn't let you represent 123.367 exactly. It just gives you enough precision that the default rounding for `%f` doesn't show the rounding error. – user2357112 Jul 01 '18 at 22:06