【问题标题】:Android square root calculation errorAndroid平方根计算错误
【发布时间】:2016-10-04 17:27:00
【问题描述】:

我想制作一个使用 Heron 算法计算平方根的 Java 应用程序。但是当我输入 9 时,它会在屏幕上打印 2.777777910232544。 当我输入 1 时,它会打印 1。现在我不知道我是否写错了代码,或者我对 Java 中的浮点数一无所知。

这是我的代码:

public class MainActivity extends AppCompatActivity {

float length1;
float width1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final TextView mainOutput = (TextView) findViewById(R.id.mainOutput);
    final EditText mainInput = (EditText) findViewById(R.id.mainInput);
    final Button wurzel2 = (Button) findViewById(R.id.wurzel2);

    assert wurzel2 != null;
    wurzel2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            for(int i = 0; i < 20; i++) {
                float inputNumber = Integer.parseInt(mainInput.getText().toString());
                length1 = 1;
                width1 = inputNumber / length1;
                float length2 = (length1 + width1) / 2;
                float width2 = inputNumber / length2;
                length1 = length2;
                width1 = width2;
            }
            double wurzel = length1 / width1;
            mainOutput.setText(String.valueOf(wurzel));
        }
    });
}
}

【问题讨论】:

  • 为什么不使用sqrt() function
  • 好吧,我基本上是想自己写sqrt()函数。
  • 为什么?它的性能肯定会低于数学库中已经存在的优化版本。
  • 我必须把它作为学校的家庭作业。我们应该使用这个算法来编写它。我知道只使用 sqrt() 函数会容易得多。我已经用 PHP 编写了它并且它工作但在 Java 中我不知道我做错了什么。
  • Android Studio calculation ???这与 Android Stdio 无关。您的 Android 应用会进行计算。这是你的代码。

标签: java android square-root


【解决方案1】:

我编写了 Heron 算法的非 Android Java 实现,该算法源自 https://en.wikipedia.org/wiki/Methods_of_computing_square_roots 上显示的算法公式

public class MyClass {
    public static void main(String[] args) {
        float x = 9;
        System.out.println(heron(x));
    }

    static float heron(float s) {
        float x = (float) 1.0; // initial approximation of result
        for (int i = 0; i < 20; i++) {
            float sDivX = s / x;
            x = (x + sDivX) / 2;
            // remove this line in production, this is just to watch progress
            System.out.println(String.valueOf(x));
        }
        return x;
    }
}

您的代码在循环内有 length1=1(您的 length1 相当于我的 x),所以 它从迭代到迭代没有任何进展。

x = s/(float)2 可能是比 1 更好的初始估计值,尤其是对于较大的值。对于较小的输入值,20 次迭代可能是多余的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-03
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多