如何在需要使用float时真正避免浮点错误? [英] How to actually avoid floating point errors when you need to use float?

查看:233
本文介绍了如何在需要使用float时真正避免浮点错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图影响3D模型的翻译,使用一些UI按钮来将位置移动0.1或-0.1。

我的模型位置是一个三维浮动,所以简单地将0.1f添加到其中一个值会导致明显的舍入错误。虽然我可以使用BigDecimal之类的东西来保持精度,但我仍然必须将其从浮点型转换回浮点型,并且总是会导致愚蠢的数字,导致我的UI看起来像一团糟。



我可以只显示所显示的值,但舍入错误只会在更多编辑时变得更糟,并且会使我的保存文件难以阅读。



那么当我需要使用float的时候,我该如何避免这些错误呢?

我会使用 code> Rational 类。那里有很多 - a>看起来应该是可行的。

Rational 被渲染成一个 float ,分母缩小为 gcd 时为一。我发布的这个分子和分母总是处于完全减少的状态,如果你总是加1/10,这应该是非常有效的。


实现将值保持为标准化(即具有一致的符号),但未减少。

您应该选择最适合您的用法的实现。 b

I am trying to affect the translation of a 3D model using some UI buttons to shift the position by 0.1 or -0.1.

My model position is a three dimensional float so simply adding 0.1f to one of the values causes obvious rounding errors. While I can use something like BigDecimal to retain precision, I still have to convert it from a float and back to a float at the end and it always results in silly numbers that are making my UI look like a mess.

I could just pretty the displayed values but the rounding errors will only get worse with more editing and they make my save files rather hard to read.

So how do I actually avoid these errors when I need to use a float?

解决方案

I would use a Rational class. There are many out there - this one looks like it should work.

One significant cost will be when the Rational is rendered into a float and one when the denominator is reduced to the gcd. The one I posted keeps the numerator and denominator in fully reduced state at all times which should be quite efficient if you are always adding or subtracting 1/10.

This implementation holds the values normalised (i.e. with consistent sign) but unreduced.

You should choose your implementation to best fit your usage.

这篇关于如何在需要使用float时真正避免浮点错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆