You are not logged in.
Hi,
if (-0.01 < x - y && x - y < 0.01)
{
print : "The numbers are close together");
}
what is the meaning of -0.01?
and how could we compared between two numbers distance using this short unknown expression?
I mean for example I'll try two close numbers but it didn't work like :
x = 1, y= 0.5
like :
(-0.01 < 1 - 0.5 && 1 - 0.5 < 0.01)
( true && false )
the result is false !!!! so the numbers are not close but they are close it's 1 and 0.5 look 0--0.5--1.5--2-2.5...
so the numbers are not close togather? is that expression wrong? and if it's wrong what is the correct one
Wisdom is a tree which grows in the heart and fruits on the tongue
Offline
Hi,
This is just a way of saying they're close if the difference is less than 0.01
Say x > y, then close if x-y < 0.01
And if x < y then close if y - x < 0.01
=> x - y > -0.01
Bob
Children are not defined by school ...........The Fonz
You cannot teach a man anything; you can only help him find it within himself..........Galileo Galilei
Sometimes I deliberately make mistakes, just to test you! …………….Bob
Offline
EPSILON = 1E-14;
r = sqrt(2.0)
if abs(r * r - 2.0) < EPSILON
output :-
sqrt(2.0) squared is approximately 2.0
this when I use java but when I use Microsoft calculator it said false! the condition would be false not true as you can see in this picture :-
also as you can see in this example :-
double x = 9.999999999999999;
if (Math.abs(x- 10.0) < EPSILON)
{
System.out.println("the number is approximately 10");
}
}
}
when I minus the 9.999999999999999 to 9.99 for example the condition will be false!
in short I just want to solve this question :-
Explain why it is more difficult to compare floating-point numbers than integers.
Write Java code to test whether an integer n equals 10 and whether a floating-point
number x is approximately equal to 10
Last edited by Hannibal lecter (2022-10-04 02:07:26)
Wisdom is a tree which grows in the heart and fruits on the tongue
Offline
I went to Wolfram-Alpha https://www.wolframalpha.com to compute
Abs(1.41421356*1.41421356 - 2) and got the result 6.7121264 * 10^(-9)
So the expression isn't less than 10^(-14). So FALSE is what I would expect.
Bob
Children are not defined by school ...........The Fonz
You cannot teach a man anything; you can only help him find it within himself..........Galileo Galilei
Sometimes I deliberately make mistakes, just to test you! …………….Bob
Offline