如何测试,如果数值转换会改变的价值? [英] How to test if numeric conversion will change value?

查看:130
本文介绍了如何测试,如果数值转换会改变的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在执行某些数据类型转换,我需要代表 UINT ULONG 小数作为IEEE 754双浮点值。我希望能够检测如果IEEE 754数据类型不能包含值之前,我进行转换。

I'm performing some data type conversions where I need to represent uint, long, ulong and decimal as IEEE 754 double floating point values. I want to be able to detect if the IEEE 754 data type cannot contain the value before I perform the conversion.

一个蛮力解决办法是换一个try-catch周围投翻番寻找发生OverflowException 。通过一定的 CLR文档阅读意味着一些转换只是默默的改变,没有任何异常值。

A brute force solution would be to wrap a try-catch around a cast to double looking for OverflowException. Reading through certain of the CLR documentation implies that some conversions just silently change the value without any exceptions.

有任何万无一失的方法来做到这一点检查?我找了完整性易于实现。我有一种感觉,我会密切读取IEEE 754规范和检查matissa并仔细李氏指数...

Is there any fool proof way to do this check? I'm looking for completeness over ease of implementation. I have a feeling I'm going to be closely reading the IEEE 754 spec and checking matissa and exponent carefully...

我要补充一点,我的 。大多数的关心准确地代表整数和浮点精度的损失是次要关注的(但仍值得考虑)

I should add, that I am most concerned with representing whole numbers accurately and that loss of floating point precision is of secondary concern (but still worth considering).

编辑:的Int32能够得到充分的体现为IEE-754。另外,小数数据类型是问题的非常重要的一部分。

Int32 is able to be fully expressed as IEE-754. Also the Decimal data type is very much part of the question.

重要更新:如果你指的是这个问题,你也应该看这个问题: IEEE-754双(64位浮点)与长(64比特整数)再访

Important Update: if you are referring to this question, you should also read this question: IEEE-754 Double (64-bit floating point) vs. Long (64-bit Integer) Revisited

它指出在一些非常大的价值,也能够通过IEEE-754精确表示,答案的一个缺陷。虽然这可能意味着该值将正确往返,我最初的目的(将它往返的JavaScript)不会。

It notes a flaw in the answer where some very large values are also able to be exactly represented by IEEE-754. While this may mean that the value will correctly round-trip, for my original purpose (will it round-trip to JavaScript) it will not.

也似乎有在的CLR System.Double类型,因为它不能正确地允许将这些值往返的错误。

Also there appears to be a bug in the CLRs System.Double type because it doesn't correctly allow these values to round-trip.

推荐答案

简单的解决方案可能是这样的(如果x是一个int ):

Simple solution could be something like (if x is an int):

if ((int)(double)x != x) { 
  // won't convert
} else {
  // will convert
}

等了很久,等。

(双)x将x转换从int到双。在(INT)然后再转换回来。所以(INT)(双)x转换成一个int到double,然后回来。基本上代码检查转换到加倍是可逆的(因此,双可以存储整型的精确值)。​​

(double)x will convert x from an int to a double. The (int) then converts it back again. So (int)(double)x converts form an int to a double and then back. Essentially the code is checking that the conversion to double is reversible (and therefore that the double can store the exact value of the int).

这篇关于如何测试,如果数值转换会改变的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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