+ 3
Weird behavior
So when I run this code, it doesn't exactly behave as I expected it to. Why? https://code.sololearn.com/cV4Qaucjz2de/?ref=app
9 ответов
+ 2
Floating point calculation can't be too precious in binary, try to format it to correct decimal point.
Eg. {0:0.000}
https://code.sololearn.com/c14zh0v8XKCk/?ref=app
+ 3
I observed that Calviղ's code is not the final solution. The last value should stop at 1, but it actually stops at 0.999.
Here are a couple of variations that will fix the for loop as well as the output.
Use this:
for(double i=0.0, j=0.0; i<=1.0; i=0.001*(++j)) {
Or this:
for(double i=0.0; i<=1.0; i=Math.Round(i+0.001,3)) {
Note also that float would suffice for this range of numbers. Using double precision is unnecessary.
+ 1
This formating is for number only
+ 1
Daniel Cooper The formatting converts double to a string in fact.
+ 1
Daniel Cooper for creating a string variable, s:
String s = String.Format("{0:0.000}", i);
https://code.sololearn.com/cqBTSM4Vwv8Y/?ref=app
+ 1
Calviղ Thanks. I was trying to convert a string to a string. No wonder it wasn't working xD
+ 1
Daniel Cooper As it's been established, the output is due to the conversion from floating point to binary where precision is limited due to fixed number of bits allotted for a given data type.
You can see these differences when comparing this same code using float and decimal types in the code link below:
https://code.sololearn.com/cXaqUFq4moAx/
You can learn more about accuracy problems with Floating Point Arithmetic in this link:
https://en.m.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems
0
Calviղ Wait, can I format a string like this?
0
Calviղ Sorry, just to be clear, I mean convert a double to a string and format it like this. Is that possible?