0

I have hit a snag in my program when this calculates I get result of 0.0

y = 1/6*Math.pow(x,3)+1/2*Math.pow(x,2)-1/3*x;

I have tried writing the equation in chunks so I can add the results up after calculation but the result just keeps ending up being 0.0 and I don't know why. Is this a syntactical error or is there a rule that I'm missing about java?.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 4
    `1/6 == 0` and `1/2 == 0` and `1/3 == 0` – user253751 Jan 19 '15 at 04:19
  • This question can't be generalized there is so many different ways of asking it, and when I asked the question I had no idea where the problem was in the equation so there is no method to asking this quesiton – Anesu Jan 19 '15 at 06:07

2 Answers2

2

When you divide two integers Java truncates the result to an integer. If you want a fractional result you need to use floating point numbers. 1/2 is 0; 1.0/2.0 is 0.5.

y = 1.0/6.0*Math.pow(x,3) + 1.0/2.0*Math.pow(x,2) - 1.0/3.0*x;
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Omg thank you so much that worked, I will need to remember that, I still have a lot of things to learn. – Anesu Jan 19 '15 at 04:25
-1
y = 1/6*Math.pow(x,3)+1/2*Math.pow(x,2)-1/3*x;

Here you are doing division of two integers, which would result in 0. Make one/both of the values to decimal (1.0/6.0 etc) and then try this. It should give the correct result. The reason is that, 1/6 will be corrected to the closest integer value, which is 0.

Yadu Krishnan
  • 3,492
  • 5
  • 41
  • 80