Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating point arithmetic not working as expected [duplicate]

The following simple floating point arithmetic operation is not working as expected.

double den = (1+j);
System.out.println(den);
den = 1/den;
System.out.println(den);

double newden = 1/(1+j);
System.out.println(newden);

The above code gives the following output.

7.0
0.14285714285714285
0.0

As shown above, the first two operations work as expected but the last doesn't. I suppose that it has something to do with the variable type but still haven't figured out the problem.

Can you please explain the behaviour of arithmetic operations in Java?

like image 756
user3540466 Avatar asked Aug 30 '26 23:08

user3540466


2 Answers

An arithmetic operation in java is done in int if there is no float/double/long involved. Hence, change one of the arg to float/double and it works as expected.

The following code would work:

double newden = 1d/(i+j);
System.out.println(newden);

From the java spec:

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules, in order:

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.
like image 51
Pankaj Singhal Avatar answered Sep 04 '26 16:09

Pankaj Singhal


This is working. If you try this by putting (double) 1/(1+j); there, you can see the result:

int j = 1;
        double den = (1+j);
        System.out.println(den);
        den = 1/den;
        System.out.println(den);

        double newden = (double) 1/(1+j);
        System.out.println(newden);

Here, your output will be:

2.0
0.5
0.5
like image 25
Vijaya Pandey Avatar answered Sep 04 '26 16:09

Vijaya Pandey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!