doubleValue不会在任何时候正确地将对象转换为双精度值 [英] doubleValue does not convert the object to a double value correctly at all times
问题描述
NSMutableArray * setOfDoubles;
添加元素如下
NSNumber * num;
num = [NSNumber numberWithDouble:someDouble];
[setOfDoubles addObject:num];
我读过的元素如下
num = [setOfDoubles lastObject];
[setOfDoubles removeLastObject];
doubleValueToUse = [num doubleValue];
我的问题有时(不总是),例如当num(作为对象)为5.1时, doubleValueToUse(作为双精度值)为5.099999999999996。我认为num(作为一个对象)的方式是5.1,是我调试的时候,当我将鼠标悬停在num的顶部,num = [setOfDoubles lastObject];它显示5.1,但在doubleValue转换后,它成为我提到的数字。有没有人知道为什么会发生这种情况?
并不是每个数字都可以使用一个float变量进行准确的表示。例如,在我们的常用十进制(base-10)系统中,您不能精确地表示1/3,使用有限数字的数字,但是在三进制(base-3)中,只有0.1。类似地,您可以使用十进制数字的有限数字编写的数字可能不一定在其二进制表示中具有有限数字位数,因此出现错误。
A如果你有兴趣的话,很少有关于这个话题的链接:
http://floating-point-gui.de/basic/
http://www.mathworks.com/support/tech-notes/1100/1108.html
http://下载。 oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html
I have an NSArray in which I would like to store double values. I defined it as follow
NSMutableArray *setOfDoubles;
I add the elements as follow
NSNumber *num;
num = [NSNumber numberWithDouble:someDouble];
[setOfDoubles addObject:num];
And I read the element as follow
num = [setOfDoubles lastObject];
[setOfDoubles removeLastObject];
doubleValueToUse = [num doubleValue];
My problem is sometimes (Not always), for example when num (as an object) is 5.1, doubleValueToUse (as a double value) is 5.099999999999996. The way I figured num (as an object) is 5.1 is that I debug and when I am hovering the mouse on top of num on the line num = [setOfDoubles lastObject]; it shows 5.1 but after doubleValue conversion it becomes the number I mentioned. Does anybody know why is this happening?
Not every number can be accurately represented using a float variable. For example, you can't precisely represent, say, 1/3 using a finite number of digits in our common decimal (base-10) system, but in ternary (base-3), it would be just 0.1. Similarly, the numbers you can write with a finite number of digits in decimal, may not necessarily have the finite number of digits in their binary representation, hence the error.
A few links on the topic if you are interested:
http://floating-point-gui.de/basic/
http://www.mathworks.com/support/tech-notes/1100/1108.html
http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html
这篇关于doubleValue不会在任何时候正确地将对象转换为双精度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!