+ 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

3rd Dec 2019, 1:44 AM
Daniel Cooper
Daniel Cooper - avatar
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
3rd Dec 2019, 2:02 AM
Calviղ
Calviղ - avatar
+ 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.
4th Dec 2019, 2:22 PM
Brian
Brian - avatar
+ 1
This formating is for number only
4th Dec 2019, 12:46 AM
Calviղ
Calviղ - avatar
+ 1
Daniel Cooper The formatting converts double to a string in fact.
4th Dec 2019, 5:59 AM
Calviղ
Calviղ - avatar
+ 1
Daniel Cooper for creating a string variable, s: String s = String.Format("{0:0.000}", i); https://code.sololearn.com/cqBTSM4Vwv8Y/?ref=app
4th Dec 2019, 6:02 AM
Calviղ
Calviղ - avatar
+ 1
Calviղ Thanks. I was trying to convert a string to a string. No wonder it wasn't working xD
4th Dec 2019, 6:38 AM
Daniel Cooper
Daniel Cooper - avatar
+ 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
8th Dec 2019, 7:36 PM
David Carroll
David Carroll - avatar
0
Calviղ Wait, can I format a string like this?
3rd Dec 2019, 8:14 PM
Daniel Cooper
Daniel Cooper - avatar
0
Calviղ Sorry, just to be clear, I mean convert a double to a string and format it like this. Is that possible?
4th Dec 2019, 3:46 AM
Daniel Cooper
Daniel Cooper - avatar