Tag: 浮点精度

将String内的数学表达式计算为Float?

我需要用Java来评估数学表达式。 问题是,表达式是一个String对象。 有没有办法取字符串”( (21 + 3) / 4 )”并对其进行评估,以便它给出6作为结果? 到目前为止这是代码。 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; class InfixApp { public static void main(String[] args) throws IOException { String input, output; while(true) { System.out.print(“Enter infix: “); System.out.flush(); input = getString(); // read a string from kbd if( input.equals(“”) ) // quit if [Enter] break; // make […]

为什么在非整数值上使用模数会失去浮点精度?

我想知道为什么我在使用这段代码时会失去精度: double x = 12.0456; // or float : same result System.out.println(x); // outputs 12.0456 obviously x %= 1; // should now be equal to 0.0456 right? System.out.println(x); // outputs 0.04560000000000031 or 0.045599937 when using float 12.0456模1应该等于0.0456对吗? 但它显示了一个略有不同的值,为什么我一直在失去精度? 我的意思是代码应该精确地减去1,直到值小于1。 但是,我发现了一种获得正确值的方法: double x = 12.0456; System.out.println(x); x %= 1; System.out.println((float)x); //outputs 0.0456 exactly 这种方式很完美,但你们有更好的解决方案吗? 我不关心我应该使用哪种浮点类型,我只是想找到一种干净的方法来获得正确的值! 我不喜欢将值转换为double然后转换为float。

浮点加法 – 给出奇怪的结果..!

执行以下代码时: public class FPoint { public static void main(String[] args) { float f = 0.1f; for(int i = 0; i<9; i++) { f += 0.1f; } System.out.println(f); } } 将显示以下输出: 1.0000001 但输出应该是1.0000000 ,对吗? 如我错了请纠正我..!!

如何在需要使用float时实际避免浮点错误?

我试图使用一些UI按钮来影响3D模型的转换,以将位置移动0.1或-0.1。 我的模型位置是一个三维浮点数,因此只需将0.1f添加到其中一个值就会导致明显的舍入误差。 虽然我可以使用像BigDecimal这样的东西来保持精度,但我仍然必须将它从浮点数转换回到最后的浮点数,它总是会导致愚蠢的数字使我的UI看起来像一团糟。 我可以很好地显示显示的值,但是舍入错误只会随着更多编辑而变得更糟,并且它们使我的保存文件难以阅读。 那么当我需要使用浮点数时,如何才能真正避免这些错误呢?

double或float数据类型在循环中没有正确加载?

在循环中,我添加0.10,直到达到所需的#,并获得索引。 这是我的代码: private static int getIndexOfUnits(float units) { int index = -1; float addup = 0.10f; for(float i = 1.00f; i < units; i=(float)i+addup) { index++; System.out.println("I = " + i + " Index = " + index); } return index; } 如果通过的单位是5.7,我看到的输出是: I = 1.0 Index = 0 I = 1.1 Index = 1 […]

为什么使用double的for循环无法终止

我正在查看旧的考试题目(目前是大学的第一年)。我想知道是否有人可以更彻底地解释为什么以下for循环不会在它应该结束时结束。 为什么会这样? 我知道它因为四舍五入错误而跳过100.0,但为什么呢? for(double i = 0.0; i != 100; i = i +0.1){ System.out.println(i); }

为什么从float转换为double会改变这个值?

我一直试图找出原因,但我不能。 有谁能够帮助我? 请看以下示例。 float f; f = 125.32f; System.out.println(“value of f = ” + f); double d = (double) 125.32f; System.out.println(“value of d = ” + d); 这是输出: 值f = 125.32 值d = 125.31999969482422

在java中操作和比较浮点数

在Java中,没有精确表示浮点运算。 例如这个java代码: float a = 1.2; float b= 3.0; float c = a * b; if(c == 3.6){ System.out.println(“c is 3.6”); } else { System.out.println(“c is not 3.6”); } 打印“c不是3.6”。 我对超过3位小数的精度感兴趣(#。###)。 我如何处理这个问题来乘以浮点数并可靠地比较它们?