在 .NET 中转换 long double
我必须将一些 C 代码(在 Linux 机器中运行)转换为 .Net,并发现一些带有 long double 的操作。它们不是特殊的运算,只是一些以很多小数结尾的乘法和除法,似乎使用该类型只是因为它的大小。
为了转换代码你会做什么?我正在考虑将这些值相乘并在最后除以看看是否有帮助,因为代码无论如何都会在最后返回短值,而且我不知道原始二进制文件是否确实使用了所有大小double 可以提供,或者如果它只是在引擎盖下使用常见的 64 位 double 。
如果您认为这不是一个好主意,您是否知道任何可用于包装和模拟 long double 的类或结构?用 C/C++ 创建包装器并从 .Net 调用它是“不可能的”。
I have to convert some C code (that ran in a Linux machine) to .Net, and found some operations with long double. They are not special operations, just some multiplications and divisions that end with a lot of decimals, it seems the type was used just because of its size.
What would you do in order to convert the code? I'm thinking of just multiply the values and divide back at the end to see if it helps since the code is anyway returning short values at the end, plus I don't know if the original binary was indeed using all the size a long double can provide or if it was just using a common 64-bit double under the hood.
If you don't think this is a good idea, do you know of any class or structure that can be used to wrap and simulate a long double? Making a wrapper in C/C++ and call it from .Net is "not possible".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最有可能的是,C long double 实际上映射到 double,因此在不了解有关计算的更多信息的情况下,我假设您可以在 C# 中使用 double。
根据我的经验,很少会发现 64 位双精度不足以满足科学或工程计算的需要。
100% 确定 double 就足够的唯一方法是研究算法,因此这个建议仅基于直觉和经验。
It's most likely that the C long double actually mapped to a double and so without knowing more about the calculations I'd assume you were fine to use double in C#.
In my experience it's very rare to find a scientific or engineering calculation for which 64 bit double is not sufficient.
The only way to be 100% certain that double is sufficient would be to study the algorithm so this advice is based on instinct and experience alone.
在 .net 中,小数是目前可用的最高精度的实际类型。小数主要用于金融计算,因为它更精确且范围更大。然而,对于科学计算,不建议这样做,因为它比 double 慢。
In .net, you have decimal which is highest precision real type available as of now. Decimal is mostly used for financial calculations as it's precise and it has larger range. However for scientific calculations it is not recommended as it is slow compared to double.
您可能尝试
System.Decimal
(在C#中又名decimal
) - 这是一个96位数字,采用以10为基数的算术(舍入等) ),使其特别适合涉及货币等事物的场景。它不映射到 IEEE,但取决于 C 编译器,long double
也不会映射到 IEEE。请注意,它是在软件中实现的。You might try
System.Decimal
(akadecimal
in C#) - this is a 96-bit number, with base-10 arithmetic (rounding etc), making it particularly suitable for scenarios involving things like currency. It doesn't map to IEEE, but depending on the C compiler, neither doeslong double
;p Note that it is implemented in software.