用java解决复杂的代数公式

dav*_*d33 4 java algebra

我试图使用Java在以下等式中求解y:

在此输入图像描述

为了可见性,我将分子和分母分成单独的变量.我需要x = -3通过x = 4以增量为单位进行计算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);
}
Run Code Online (Sandbox Code Playgroud)

我得到的值不是预期的.

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
Run Code Online (Sandbox Code Playgroud)

使用在线工具我为X = 0计算得到2而不是-2.我如何计算数字有什么问题吗?

Pau*_*aul 9

你在实现表达式时犯了一个错误.

... - ( (4 * x) + 12 )
Run Code Online (Sandbox Code Playgroud)

应该

... - (4 * x) + 12
Run Code Online (Sandbox Code Playgroud)

或者在完整的表达中:

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

同样如@JacobG所述:

1/2计算结果为0,因为它是整数除法.如果您评估for,这没有任何区别x = 0.这可以使用0.5替代来纠正.


Jac*_* G. 6

你的等式中有一个小错字:

1/2
Run Code Online (Sandbox Code Playgroud)

等于0Java; 看:为什么1/3 == 0的结果?

要解决此问题,您只需键入0.5或使用1 / 2D1D / 2.

请参阅Paul关于代码的另一个问题的答案.

  • 非常感谢.保罗的回答就是这个问题.你不知道这是多么头疼. (2认同)