Math.pow 使用小数指数

Math.pow using fractional exponents

这是我写的第一个代码。这是我的代码的一部分,用于在用户给出体积值后计算立方体和四面体的边长,但是输出不正确。我很确定我的方程是正确的,也许我使用的 Math.pow 方法不正确?

System.out.println("Now, please enter a volume for side or diameter calculation, then press ENTER: ");

volume = input.nextDouble();
cubeSide = Math.pow(volume, (1/3));
sphereDiameter = Math.pow(volume / PI * 6, (1/3));
tetSide = SQRT_2 * Math.pow(3 * volume, (1/3));

System.out.println("");
System.out.println("The Side of your CUBE is : " + cubeSide);
System.out.println("");
System.out.println("The Diameter of your SPHERE is : " + sphereDiameter);
System.out.println("");
System.out.println("The Side of your TETRAHEDRON is : " + tetSide);

关于如何获得正确输出的任何想法?

1/30 - 当被除数和除数都是整数时,/ 执行整数除法。您想要 1.0 / 31 / 3.01.0 / 3.0,其计算结果为 0.3333333-ish。

你的问题就是这个问题的一个例子Division of integers in Java

基本上,您需要将 Math.pow() 的 1/3 部分转换为双倍,因为如果默认情况下您不这样做,它会将结果作为整数(始终为 0)。

例如:

    double volume = 15.34;
    double fraction = (double) 1/3;
    double cubeSide = Math.pow(volume,fraction);
    System.out.println(cubeSide);

输出为

2.4847066359757295

否则输出始终为 1.0。这是任何数字上升到零的结果。

如您的评论所述,当输入为:

1000

输出应该是一个整体:

10

但实际上是:

9.999999999999998

最简单的解决方案可能只是:

float roundedValue = Math.round(cubeSide);

然后说:那不是我的问题。但我们想了解正在发生的事情。与这个世界上的大多数事物一样,您不是第一个面临这个问题的人。让我们做一些研究,发现在 Whosebug 中有人问过它:

  • Floating point arithmetic not producing exact results
  • Is floating point math broken?

第一个link,建议阅读What Every Computer Scientist Should Know About Floating-Point Arithmetic

那些知识比我多的智者的话我就不重复了,所以我强烈推荐你阅读上面的links。