java - 实现二次算法

标签 java algorithm math quadratic coefficients

我正在阅读 Robert Sedgewick 和 Kevin Wayne 合着的编程入门书籍。

在其中一个例子中,他们实现了一个二次类,如下所示:

public class Quadratic
{
    public static void main(String[] args)
    {
        double b = Double.parseDouble(args[0]);
        double c = Double.parseDouble(args[1]);
        double discriminant = b * b - 4.0 * c;
        double d = Math.sqrt(discriminant);
        System.out.println((-b + d) / 2.0);
        System.out.println((-b - d) / 2.0);
    }
}

作者省略了二次公式的'a'系数。这是因为可以抵消“a”系数(分子/分母)吗?

根据反馈……以下是否是正确的解决方案:

public static void main(String[] args)
    {
        double b = Double.parseDouble(args[0]);
        double c = Double.parseDouble(args[1]);
        double a = Double.parseDouble(args[2]);
        double discriminant = b * b - 4.0 * a * c;
        double d = Math.sqrt(discriminant);
        System.out.println((-b + d) / (2.0 * a));
        System.out.println((-b - d) / (2.0 * a));
    }

最佳答案

不,作者可能以不同的方式实现了该算法。假设一般情况下,a 不能被取消,因为 -b 因素不包含 a。

求二次方程根的公式是:-

roots = (-b +(-) sqrt((b^2) - (4*a*c))) / (2*a).
     // here - alongwith + represents how to find second root.

我建议你通过常用的方式。如果作者使用了不同的约定,请不要遵循。

请遵循标准/通用方式。这很容易理解。

Based on the feedback… Would the following be the correct solution:..

您作为编辑添加到问题中的解决方案似乎是正确的。所以,我建议你走那条路。

关于java - 实现二次算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35874045/

相关文章:

c# - 如何提取数字的位值?

java - imgscalr AsyncScalr 的示例代码

java - 带有 rtl 布局方向的 api 17 和 18 的 Tablayout 问题

python - 螺旋图案 : how do I find a number given coordinates?

arrays - 如何为已打乱的数组添加依赖项?

algorithm - 如何标准化 for 循环?

c# - 如何从另一个矩形中减去一个矩形?

Javascript Math.cos 和 Math.sin 不准确。有什么解决办法吗?

java - 为什么有 <?在 java.util.Collections.unmodifiableList API 中扩展 T> 而不是 <T>

java - 字符编码不适用于 PrimeFaces CellEditor 组件