-2

Probably a very simple math question, but this has me a little bit confused.

Can anybody explain to me why this:

public class volumesphere
{
public static void main(String[] args)
{
    double radius = 30.5;
    double PI = Math.PI;
    double volume = (4.0/3) * PI * Math.pow(radius, 3);

    System.out.println(volume);
}
}

Is different to this?:

public class volumesphere
{
public static void main(String[] args)
{
    double radius = 30.5;
    double PI = Math.PI;
    double volume = (4/3) * PI * Math.pow(radius, 3);

    System.out.println(volume);
}
}

Specifically in the line:

double volume = (4/3) * PI * Math.pow(radius, 3);

volume in the first case returns the correct answer at about 1.19*10^5. However, the latter returns a completely different result, around 8.9*10^4.

Can anybody explain this to me please?

J.Davies
  • 41
  • 4
  • `4/3` is integer division, it yields `1` . – Arnaud Sep 25 '17 at 10:22
  • Because `4` and `3` are both `int`s, so you will get a rounding error. Using `4.0` you are saying that you want a floating point division rather than an integer division and won't get the same rounding error. – RaminS Sep 25 '17 at 10:22

2 Answers2

1

Its because 4/3 is 1 and not 1.333....

When you do int / int, you get an int as the result.
On the contrary 4.0 / 3 is 1.333..., because the types are double / int and therefore result in a double.

nyronium
  • 1,130
  • 2
  • 8
  • 24
0

In 4/3 the 4 is an Integer

In 4.0/3 the 4 is a Double

As integer it won't have decimal values, as double it will ^^

The result is: 1,333333333333 for both the operations, but as Integer it won't get the decimal part.

Marco Salerno
  • 4,889
  • 2
  • 8
  • 27