4

I am trying to solve for y in the following equation using Java:

enter image description here

For the sake of visibility I divided the numerator and denominator into separate variables. I need to compute for x = -3 through x = 4 moving in increments of 0.5.

for(double x = -3; x <= 4; x += .5)
{
    // Now we compute the formula for all values in between -3 and 4 in increments of 0.5

    double top = ( 9 * Math.pow(x, 3) ) - ( 27 * Math.pow(x, 2) ) - ( (4 * x) + 12 );
    double bottom = ( Math.pow(( 3 * Math.pow(x, 2) + 1 ) , 1/2) + Math.abs( 5 - (Math.pow(x, 4)) ) );

    double y = top / bottom;

    System.out.print("X = " + x + "\t Y = " + y);
}

The values I get are not as intended.

X = -3.0     Y = -6.311688311688312 
X = -2.5     Y = -8.880570409982175   
X = -2.0     Y = -15.333333333333334      
X = -1.5     Y = -91.41176470588235 
X = -1.0     Y = -8.8   
X = -0.5     Y = -3.0105263157894737 
X = 0.0      Y = -2.0   
X = 0.5      Y = -3.305263157894737   
X = 1.0      Y = -6.8    
X = 1.5      Y = -45.529411764705884     
X = 2.0      Y = -4.666666666666667  
X = 2.5      Y = -1.429590017825312  
X = 3.0      Y = -0.3116883116883117    
X = 3.5      Y = 0.19940094137783482     
X = 4.0      Y = 0.4603174603174603

Using an online tool I computed for X = 0 and got 2 instead of -2. Is there something wrong with how I did the math?

davidxd33
  • 1,156
  • 2
  • 19
  • 38

2 Answers2

9

You made a mistake while implementing the expression.

... - ( (4 * x) + 12 )

Should be

... - (4 * x) + 12

Or in the complete expression:

double top = ( 9 * Math.pow(x, 3) ) - ( 27 * Math.pow(x, 2) ) - (4 * x) + 12;

Also as noted by @JacobG:

1/2 evaluates to 0, since it's an integer-division. This doesn't make any difference if you evaluate the for x = 0 though. This can be corrected using 0.5 instead.

Paul
  • 13,100
  • 3
  • 17
  • 34
  • That solved is correctly for x = 0 however still not for the other values such as ``x = -2.5`` which is supposed to equal ``−7.463007``. Thanks. – davidxd33 Jun 04 '18 at 20:36
  • 1
    @davidxd33 Just updated my answer. There's actually another mistake, noticed in [JacobG's answer](https://stackoverflow.com/a/50688364/4668606) – Paul Jun 04 '18 at 20:37
  • Thanks a lot for your quick help, I got it. – davidxd33 Jun 04 '18 at 20:38
  • @ifly6 Correct. But you forgot the minus. `- ( (4 * x) + 12 )` is the complete expression that needs to be corrected. I'll update the answer. With the minus it does make a difference – Paul Jun 04 '18 at 20:39
6

There's a small typo in your equation:

1/2

Is equal to 0 in Java; see: Why is the result of 1/3 == 0?

To fix this, you can just type 0.5, or use 1 / 2D or 1D / 2.

See Paul's answer for another issue with your code.

Jacob G.
  • 26,421
  • 5
  • 47
  • 96
  • 2
    Thanks a lot. That was the problem along with Paul's answer. You have no idea how much of a headache this was. – davidxd33 Jun 04 '18 at 20:37