什么时候使用浮点精度数据类型合适? [英] When is it appropriate to use floating precision data types?

查看:236
本文介绍了什么时候使用浮点精度数据类型合适?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很明显,在处理例如货币金额时,不应使用浮动精度,因为在使用该金额进行计算时,精度的差异会导致不准确.

It's clear that one shouldn't use floating precision when working with, say, monetary amounts since the variation in precision leads to inaccuracies when doing calculations with that amount.

也就是说,什么是可接受的用例?而且,在决定时应牢记的一般原则是什么?

That said, what are use cases when that is acceptable? And, what are the general principles one should have in mind when deciding?

推荐答案

浮点数应用于其设计目的:计算所需要的是固定的 precision 且仅注意您的答案在一定的公差范围内是准确的.如果在所有情况下都需要确切的答案,则最好使用其他方法.

Floating point numbers should be used for what they were designed for: computations where what you want is a fixed precision, and you only care that your answer is accurate to within a certain tolerance. If you need an exact answer in all cases, you're best using something else.

以下是您可以使用浮点的三个域:

Here are three domains where you might use floating point:

  1. 科学模拟
    科学应用程序需要进行大量的数字运算,并且经常使用复杂的数值方法来求解微分方程组.您通常在这里使用双精度浮点数.

  1. Scientific Simulations
    Science apps require a lot of number crunching, and often use sophisticated numerical methods to solve systems of differential equations. You're typically talking double-precision floating point here.

游戏
将游戏视为可以欺骗的模拟游戏.如果物理足够好"以至于看起来真实,那么游戏就可以了,您可以在用户体验中弥补准确性方面的不足.游戏通常使用单精度浮点数.

Games
Think of games as a simulation where it's ok to cheat. If the physics is "good enough" to seem real then it's ok for games, and you can make up in user experience what you're missing in terms of accuracy. Games usually use single-precision floating point.

统计数据
像科学应用程序一样,统计方法也需要很多浮点数.许多数值方法是相同的.应用程序域是不同的.您可以在金融应用程序以及要分析大量调查数据的任何领域中找到大量统计数据和蒙特卡洛模拟.

Stats
Like science apps, statistical methods need a lot of floating point. A lot of the numerical methods are the same; the application domain is just different. You find a lot of statistics and monte carlo simulations in financial applications and in any field where you're analyzing a lot of survey data.

浮点数并非易事,对于大多数业务应用程序,您实际上不需要了解所有这些细微之处.您只知道不能精确地在浮点数中表示一些十进制数字就可以了,并且应该确保对价格和类似的东西使用某种十进制类型.

Floating point isn't trivial, and for most business applications you really don't need to know all these subtleties. You're fine just knowing that you can't represent some decimal numbers exactly in floating point, and that you should be sure to use some decimal type for prices and things like that.

如果您真的想深入了解细节并了解所有折衷和陷阱,请查看经典的每个程序员应该了解的浮点数,或者在数值分析

If you really want to get into the details and understand all the tradeoffs and pitfalls, check out the classic What Every Programmer Should Know About Floating Point, or pick up a book on Numerical Analysis or Applied Numerical Linear Algebra if you're really adventurous.

这篇关于什么时候使用浮点精度数据类型合适?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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