我跑在我的iPhone的代碼被重新分析後:DBL_MAX失去其精度顯著部分從字符串
double d = DBL_MAX;
NSString *s = [NSString stringWithFormat:@"%.0f", d];
double dp = atof([s cStringUsingEncoding:[NSString defaultCStringEncoding]]);
NSString *pe = d == dp ? @"YES" : @"NO";
double one = 1;
double dpd = dp/one;
NSString *de = d == dpd ? @"YES" : @"NO";
NSLog(@"### Parsed are equal: %@, divided are equal: %@", pe, de);
NSLog(@"D : %.0f", d);
NSLog(@"DP : %.0f", dp);
NSLog(@"DPD : %.0f", dpd);
...並獲得該輸出:
### Parsed are equal: NO, divided are equal: NO
D : 17976931348623157081452742373170435679807056752584499659891747680315726078002853876058955863276687817154045895351438246423432132688946418276846754670353751698604991057655128207624549009038932894407586850845513394230458323690322294816580855933212334827479
DP : 17976931348623155723920577891946972866121062246621938439403251722449088432276750723756897307653964877256701669823356283705419341284625019355047863102662518251134787976961389628366367996124520722972986881016593281354069269901878996004952428787693676134400
DPD : 17976931348623155723920577891946972866121062246621938439403251722449088432276750723756897307653964877256701669823356283705419341284625019355047863102662518251134787976961389628366367996124520722972986881016593281354069269901878996004952428787693676134400
爲什麼的printf()
/atof()
序列損失精度(I假設stringWithFormat
確實printf
內部)?它不僅發生在DBL_MAX上,而且發生在每一個非常大的數字上(即10000
它按預期工作,而DBL_MAX/2
則沒有)。有沒有辦法避免它?
如果使用'-doubleValue'而不是'atof()'怎麼辦? – 2012-03-12 16:40:53
@ RichardJ.RossIII:沒有任何變化。輸出完全相同 – 2012-03-12 16:48:59
@sch,在900719925474091(2^53-1)之後,整數中有空洞,可以用雙精度表示。保留往返輸入 - >輸出的輸入值是不可能的。但是Sergey做了一個輸出,然後是一個輸入。可以實現輸入和輸出,以便往返保存該值。這顯然沒有完成。 – AProgrammer 2012-03-12 17:28:20