C# 何时使用浮动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/407970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 02:12:39  来源:igfitidea点击:

When to use a Float

c#typesfloating-point

提问by Papa Burgundy

Years ago I learned the hard way about precision problems with floats so I quit using them. However, I still run into code using floats and it make me cringe because I know some of the calculations will be inaccurate.

几年前,我通过艰苦的方式学习了有关浮点数精度问题的方法,因此我不再使用它们。但是,我仍然遇到使用浮点数的代码,这让我感到害怕,因为我知道某些计算会不准确。

So, when is it appropriate to use a float?

那么,什么时候使用浮点数合适呢?

EDIT:As info, I don't think that I've come across a program where the accuracy of a number isn't important. But I would be interested in hearing examples.

编辑:作为信息,我认为我没有遇到过一个数字的准确性不重要的程序。但我有兴趣听听例子。

采纳答案by Tamas Czinege

Short answer: You only have to use a floatwhen you know exactly what you're doing and why.

简短回答:只有当您确切地知道自己在做什么以及为什么这样做时,您才需要使用浮点数

Long answer: floats(as opposed to doubles) aren't really used anymore outside 3D APIs as far as I know. Floats and doubles have the same performance characteristics on modern CPUs, doubles are somewhat bigger and that's all. If in doubt, just use double.

长答案:就我所知,在 3D API 之外不再真正使用floats(而不是doubles)。浮点数和双精度数在现代 CPU 上具有相同的性能特征,双精度数稍大一些,仅此而已。如果有疑问,只需使用 double。

Oh yes, and use decimalfor financial calculations, of course.

哦,是的,当然,使用十进制进行财务计算。

回答by Mehrdad Afshari

There are many cases you would want to use a float. What I don't understand however, is what you can use instead. If you mean using doubleinstead of float, then yeah, in most cases, you want to do that. However, doublewill also have precision issues. You should use decimalwhenever the accuracy is important.

在很多情况下,您会想要使用float. 然而,我不明白的是你可以使用什么来代替。如果你的意思是使用double而不是float,那么是的,在大多数情况下,你想这样做。但是,double也会有精度问题。您应该decimal在准确性很重要的时候使用。

floatand doubleare very useful in many applications. decimalis an expensive data type and its range (the magnitude of the largest number it can represent) is less than double. Computers usually have special hardware level support for those data types. They are used a lotin scientific computing. Basically, they are primary fractional data types you want to use. However, in monetary calculations, where precision is extremely important, decimalis the way to go.

float并且double在许多应用中非常有用。decimal是一种昂贵的数据类型,其范围(它可以表示的最大数字的大小)小于double。计算机通常对这些数据类型有特殊的硬件级支持。它们在科学计算中被大量使用。基本上,它们是您要使用的主要小数数据类型。然而,在货币计算中,精确度极其重要,这才decimal是正确的方法。

回答by U62

All floating point calculations are inaccurature in a general case, floats just more so than doubles. If you want more information have a read of What Every Computer Scientist Should Know About Floating-Point Arithmetic

在一般情况下,所有浮点计算都是不准确的,浮点数比双精度高。如果您想了解更多信息,请阅读 What Every Computer Scientist should Know About Floating-Point Arithmetic

As for when to use floats - they are often used when precision is less important than saving memory. For example simple particle simulations in video games.

至于何时使用浮点数 - 它们通常在精度不如节省内存重要时使用。例如,视频游戏中的简单粒子模拟。

回答by John D. Cook

The most common reason I could think of is to save space. Not that this is often worth worrying about, but in some instances it matters. A float takes up half as much memory as a double, so you can get twice as many in the same space. For example, I've had an array of numbers that was too big to fit into RAM as doubles but fit as an array floats.

我能想到的最常见的原因是节省空间。并不是说这通常值得担心,但在某些情况下它很重要。float 占用的内存是 double 的一半,因此您可以在同一空间中获得两倍的内存。例如,我有一个数字数组,它太大而无法作为双精度放入 RAM,但适合作为数组浮点数。

回答by nimrodm

Use float for performance and size. If you can manage the precision loss.

使用 float 来提高性能和大小。如果您可以管理精度损失。

While it is true that a modern processor takes the same amount of time to process single and double precision opertions, you can sometimes get twicethe throughput if you use floats with SIMD (MMX/SSE/etc. on x86) instructions.

虽然现代处理器处理单精度和双精度运算所需的时间确实相同,但如果您使用带有 SIMD(x86 上的 MMX/SSE/等)指令的浮点数,有时可以获得两倍的吞吐量。

SSE registers are 128 bits wide, and can hold 4 floatsor 2 doubles. Thus, if used correctly, you can do twice as many operations with floats as compared to doubles.

SSE 寄存器为 128 位宽,可以容纳4 个浮点数2 个双精度数。因此,如果使用得当,您可以使用浮点数进行两倍于双精度数的操作。

The size reduction (4 bytes instead of 8) becomes important when dealing with very large data sets (and size reduction usually improves performance as well due to caching, etc.)

在处理非常大的数据集时,减少大小(4 个字节而不是 8 个字节)变得很重要(并且由于缓存等原因,大小减少通常也会提高性能)

回答by ILoveFortran

First, never use floats or doubles if you want to represent decimal values exactly - use either integer types (int, long etc) or decimal (which is just an integer type with a scaling factor). Floats and doubles are converted internally to an exponential representation in base 2 and numbers represented exactly in an exponential representation in base 10 cannot in general be represented exactly. (E.g., the number 10 is only represented approximately by floats or doubles).

首先,如果您想精确地表示十进制值,切勿使用浮点数或双精度数 - 使用整数类型(int、long 等)或小数(这只是具有缩放因子的整数类型)。浮点数和双精度数在内部转换为以 2 为基数的指数表示形式,而以 10 为基数的指数表示形式准确表示的数字通常无法准确表示。(例如,数字 10 仅由浮点数或双精度数近似表示)。

Second, in terms of precision it depends on what you need. I don't agree with your sentiment that there are never calculations where precision does not matter. You normally have a specific need that your final result is accurate to say, 3 digits. It does not make sense to look for the highest precision possible if your input has only limited accuracy - say you weigh some 5g of flour and your scale only has an accuracy to 0.5g. That said, intermediate calculation usually benefit from higher precision but something that is more important than high precision if quite often speed.

其次,就精度而言,这取决于您的需求。我不同意你的观点,即从来没有精确度无关紧要的计算。您通常有一个特定的需求,即您的最终结果准确地说是 3 位数。如果您的输入准确度有限,那么寻找可能的最高精度是没有意义的 - 假设您称重约 5 克面粉,而您的秤的准确度仅为 0.5 克。也就是说,中间计算通常受益于更高的精度,但如果通常速度更快,则比高精度更重要。

Third, when preforming a series of calculations, say within a loop, you need to know what you are doing when dealing with any inexact calculations - you will incur round-off errors and some algorithms may not arrive at an answer to any degree of precision. Understanding these issues in detail may require a course in numerical analysis. This does not depend on whether you choose floats or doubles for your calculations.

第三,在执行一系列计算时,例如在循环中,您需要知道在处理任何不精确计算时您在做什么 - 您会产生舍入误差,并且某些算法可能无法得出任何精度的答案. 详细了解这些问题可能需要数值分析课程。这并不取决于您为计算选择浮点数还是双数。

For floating point calculations I would usually go with doubles since they are more general and faster than floats. However, floats are smaller and if you need to store a lot of them they are the choice to prevent performance issue due to cache misses.

对于浮点计算,我通常会使用双精度数,因为它们比浮点数更通用且速度更快。但是,浮点数较小,如果您需要存储大量浮点数,它们是防止因缓存未命中而导致性能问题的选择。

To my knowledge, floating point processing is supported in hardware for doubles but not floats, so using floats incurs a conversion to double. However, some routines would stop sooner when calculating a value iteratively when you pass a float, since this implies that you only want about 8 digits precision vs. about 16 for doubles.

据我所知,硬件支持双精度浮点处理,但不支持浮点数,因此使用浮点数会导致转换为双精度数。但是,当您传递一个浮点数时,在迭代计算一个值时,某些例程会更快地停止,因为这意味着您只需要大约 8 位精度,而双精度则需要大约 16 位精度。

回答by ILoveFortran

There is in fact one thing where it is still common to use floats aka "single precision" with 32 bits: Graphic applications and printing.

事实上,有一件事情仍然普遍使用 32 位浮点数,即“单精度”:图形应用程序和打印。

The other reason are graphic cards with their GPUs. The smaller the datatype, the faster the operation because less bits must be transported. Integer datatypes have problems with High Dynamic Range Images: The eye is able to function over a luminosity range of 1: 10^13 and discerns ca. 4000 levels. So while integer datatypes can store the number of levels they are unable to store the background brightness while floats have no problems with that. In fact IEEE 754R allows a new "half precision" float with 16 bits and a 10 bit mantissa which loses some precision but would allow an even greater speed. OpenGL and DirectX e.g. use floats extensively. The eye is very forgiving with artifacts, so no problem there.

另一个原因是带有 GPU 的显卡。数据类型越小,操作越快,因为必须传输的位越少。整数数据类型在高动态范围图像方面存在问题:眼睛能够在 1:10^13 的光度范围内发挥作用,并能识别大约 4000 级。因此,虽然整数数据类型可以存储级别数,但它们无法存储背景亮度,而浮点数则没有问题。事实上,IEEE 754R 允许使用 16 位和 10 位尾数的新“半精度”浮点数,这会降低一些精度,但会允许更高的速度。OpenGL 和 DirectX 例如广泛使用浮点数。眼睛对伪影非常宽容,所以没问题。

All other media building on graphics are inheriting floats as convienient measure. The mantissa has 24 bits allowing therefore 2^24 = 16,7 millions consecutive steps. If you have a printer with 2000 dpi resolution, you still are able to print 213x213 m sheets. More than enough precision.

所有其他建立在图形上的媒体都继承了浮动作为方便的措施。尾数有 24 位,因此允许 2^24 = 1670 万个连续步骤。如果您有一台分辨率为 2000 dpi 的打印机,您仍然可以打印 213x213 米的纸张。精度绰绰有余。