4 ms·
> That's true for every floating point number in every programming language you have ever used, though. Alright, if "you" have only ever used python. In C, fo
by enriquto 3y ago
> That's true for every floating point number in every programming language you have ever used, though.
Alright, if "you" have only ever used python. In C, for example, we have hexadecimal floating point literals that represent all floats and doubles exactly (including infinities and nans that make the json parser fail miserably).
- legobmw99 3y agoIf you use the same syntax as OP, C’s parser will also round that literal. The existence of a hex literal for floats is something orthogonal
- codetrotter 3y ago> we have hexadecimal floating point literals that represent all floats and doubles exactly How do you do that? A couple of resources I found but which I’m not sure if are about exactly what you speak of https://stackoverflow.com/questions/65480947/is-ieee-754-representation-used-in-c/65481061 https://stackoverflow.com/questions/65480947/is-ieee-754-rep... https://gcc.gnu.org/onlinedocs/gcc/Hex-Floats.html https://gcc.gnu.org/onlinedocs/gcc/Hex-Floats.html Furthermore, what exactly do you mean by “all floats and doubles exactly”?
- enriquto 3y agoYes, I was talking about what is described in your resources. You can do this: // define a floating-point literal in hex and print it in decimal float x = 0x1p-8; // x = 1.0/256 printf("x = %g\n", x); // prints 0.00390625 // define a floating point literal in decimal and print it in various ways float y = 0.3; // non-representable, rounded to closest float printf("y = %g\n", y); // 0.3 (the %g format does some heuristics) printf("y = %.10f\n", y); // 0.3000000119 printf("y = %.20f\n", y); // 0.30000001192092895508 printf("y = %a\n", f); // 0x1.333334p-2
- codetrotter 3y agoSo for example if you make a variable that has the value parent commenter used 100000.000000000017 And then you print it. Does it preserve the exact value?
- enriquto 3y agoYour question is ambiguous for two different reasons. First, this value is not representable as a floating-point number, so there's no way that you can even store it in a float. Second, once you have a float variable, you can print it in many different ways. So, the answer to your question is, irremediably, "it depends what you mean by exact value". If you print your variable with the %a format, then YES, the exact value is preserved and there is no loss of information. The problem is that the literal that you wrote cannot be represented exactly. But this is hardly a fault of the floats. Ints have exactly the same problem: int x = 2.5; // x gets the value 2 int y = 7/3; // same thing
- codetrotter 3y agoSo in other words, is it fair to say that this situation is not much different from what you get with Python?
- deleted 3y ago[deleted]