I'm currently given the task of checking for an answer and accepting it if it doesn't differ by no more than 0.01 .. below you will find my current code:
So I have set my answer as '123'. However, when I run and give the response of 123.01 which should accept it since it's the minimum, it outputs 'false'.
I feel like I'm missing something so simple yet I can't figure it out.. Is it because of rounding at one point when parsing the string to a double?...
I appreciate any help I can receive.
Junilu Lacar wrote:Floating point numbers are imprecise so there's really no guarantee that you'll get exactly what you're expecting.
This is what I get on my MacBook Pro:
Edit: Maybe "imprecise" is the wrong word -- look up floating point error to see what I really meant to say.
Thanks for your reply.
So is my current code as good as its possibly going to get? or is there anything else I can do other than changing the value of the 'maxDifference'.
Carey Brown wrote:If you have to be "precise", check out API for BigDecimal. It looks like you're getting your input from the console as a String which would work great with BigDecimal because its constructor takes a String.
Would I have to change my 'maxDifference to a 'BigDecimal' as well? This is what I currently have:
However, I'm still not able to compare by 'absoluteResult' to 'maxDifference'.
Carmine Gendry wrote:
you should probably change
And then change
The way you had it you were converting (double)0.01 to a BigDecimal in a way that would introduce floating point errors.