如何在C#中获得正确的除法结果?
问题描述:
Hello Everyone,
我有以下问题:
Hello Everyone,
I have the following issue:
float increment = 0.00025f;
float sampleFreq = 1.f / increment;
[+] sampleFreq = 3999.99976
而不是4000为什么?
如何获得4000预期结果(不是通过舍入方法)?
当然是傻瓜。
非常感谢您提前。
MiQi
我尝试了什么:
我尝试过双倍的,相同的结果。
and not 4000 why ?
How may I have the 4000 expected result (not via a rounding method) ?
Certainly something stupid.
Thank you very much in advance.
MiQi
What I have tried:
I have tried with double, same result.
答
它有点数学,但浮点数和双精度数是浮点数类型,它们具有基数2指数,而不是我们人类习惯的基数10。有些数字不能准确地表示在这里(在我们的基数10中也是如此,想想1/3 = 0.33333333333 ......)并且在那里你会得到一些准确性损失。
这是使用浮点数的典型代表,你必须接受一个误差范围,并注意平等运算符之类的东西。
您可以尝试在.NET中使用十进制类型。这使用了基数为10的指数,因此其行为方式也是如此(大多数情况下),但它在占用空间和性能方面都有成本。
It's a bit mathematical, but floats and doubles are floating point types which have a base 2 exponent as opposed to the base 10 we humans are used to. Some numbers can't be represented exactly in this (and also in our base 10 for that matter, think 1/3 = 0.33333333333....) and where that happens you get some accuracy loss.
This is typical of working with floating point numbers, you have to accept a margin of error and be careful with things like equality operators.
You could try using the decimal type in .NET. This uses a base 10 exponent so behaves the way you would expect it too (mostly), but it comes with a cost in terms of footprint and performance.
因为你正在使用浮点数数据类型。它不能完全代表浮点数。阅读:这里 [ ^ ]和这里 [ ^ ]。
想一想。你如何用有限的位表示无限数量的值?你不能。牺牲必须使数据类型能够代表最常用的各种值,并提供一定程度的准确性。
你可以使用十进制类型 [ ^ ]。它是一个128位类型,为财务目的提供更高的准确性,但它可以表示的值范围更小。
Because you're using the float data type. It can't represent floating point numbers exactly. Read up on it: here[^] and here[^] .
Think about it. How you do represent an infinite number of values in a finite number of bits? You can't. Sacrifices have to be made to make a data type that can represent a wide range of values that are most commonly used and offer some degree of "accuracy".
You can use the decimal type[^] instead. It's a 128-bit type, made for higher accuracy for things like financial purposes, but has a smaller range of values it can represent.
float和double的精度是不够的。
The precision of float and double is not sufficient.
decimal increment = 0.00025M;
decimal sampleFreq = 1M / increment;
使用小数代替。
Use decimal instead.