C# 有无符号双精度数吗?
我需要使用无符号双精度,但事实证明 C# 不提供这样的类型。
有谁知道为什么?
I need to use an unsigned double but it turns out C# does not provide such a type.
Does anyone know why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如 Anders Forsgren 所指出的,IEEE 规范中没有无符号双精度数(因此 C# 中也没有)。
您始终可以通过调用 Math.Abs() 获得正值,并且您可以将双精度数包装在结构中并在那里强制执行约束:
As pointed out by Anders Forsgren, there is no unsigned doubles in the IEEE spec (and therefore not in C#).
You can always get the positive value by calling Math.Abs() and you could wrap a double in a struct and enforce the constraint there:
浮点数只是 IEEE 754 规范的实现。据我所知,不存在无符号双精度之类的东西。
http://en.wikipedia.org/wiki/IEEE_754-2008
为什么需要无符号浮点数?
Floating point numbers are simply the implementation of the IEEE 754 spec. There is no such thing as an unsigned double there as far as i know.
http://en.wikipedia.org/wiki/IEEE_754-2008
Why do you need an unsigned floating point number?
我推出了 @Isak Savo 的更详细的实现,并进行了一些调整。不确定它是否完美,但这是一个很好的起点。
至于为什么需要无符号双精度,请考虑在大多数应用程序中 UI 元素的宽度和高度尺寸不能为负数,因为这是不合逻辑的;那么,为什么在不需要的地方支持负数呢?
某些值(例如
PositiveInfinity
和NaN
)可能仍然适用;因此,我们为它们提供直观的参考。double
和UDouble
之间的最大区别是UDouble
不需要常量NegativeInfinity
(或者至少我假设这么多;毕竟我不是数学家)并且MinValue
常量只是0
。另外,Epsilon 是正数,但我不确定在与无符号数相同的上下文中使用它是否合乎逻辑。请注意,此实现会自动截断负数,如果您尝试设置为
NegativeInfinity
,则会引发异常。I rolled out a more detailed implementation of @Isak Savo's with tweaks here and there. Not sure if its perfect, but it's a great place to start.
As to why one would need an unsigned
double
, consider that width and height dimensions of UI elements cannot be negative in most applications as that would be illogical; why, then, support negative numbers where they're not needed?Some values like
PositiveInfinity
andNaN
may still be applicable; therefore, we provide intuitive references to them. The big difference betweendouble
andUDouble
isUDouble
wouldn't need the constantNegativeInfinity
(or at least I assume this much; I am not a mathematician, after all) andMinValue
constant is simply0
. Also,Epsilon
is positive, though, I am uncertain whether or not it is logical to use in the same context as unsigned numbers.Note, this implementation automatically truncates negative numbers and an exception is thrown if you attempt to set to
NegativeInfinity
.在我听说过的任何语言或系统中都不存在“无符号双精度”这样的东西。
如果您想强制执行参数为正的约束,则需要通过运行时检查来实现。
There is no such thing as an unsigned double in any language or system that I have ever heard of.
If you want to enforce a constraint that the parameter is positive, then you need to do that with a runtime check.