如何在iOS上以全精度打印双精度

如何在iOS上以全精度打印双精度

本文介绍了如何在iOS上以全精度打印双精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试用例:

  NSLog(@%f,M_PI); 
NSLog(@%@,[NSString stringWithFormat:@%f,M_PI]);
NSLog(@%@,[NSNumber numberWithDouble:M_PI]);

结果:

结论:



1)通过NSLog()或[NSString stringWithFormat]打印提供非常低的精度...



2) NSNumber numberWithDouble]提供了更好的精度...



我希望得到更接近原始值的结果:3.14159265358979323846264338327950288(如math.h中定义) / p>

任何线索?

解决方案

因为这是 printf 从C继承的默认舍入长度。



第三行显示最大有用数据精度 - IEEE 754 64位浮点数的精度略小于16位十进制数,因此 math.h 中的文字的所有数字都是无意义的(也许他们可以被视为防范未来的一种可能的未来重新定义以更精确的格式)。


Test case:

NSLog(@"%f", M_PI);
NSLog(@"%@", [NSString stringWithFormat:@"%f", M_PI]);
NSLog(@"%@", [NSNumber numberWithDouble:M_PI]);

Results:

Conclusions:

1) Printing via NSLog() or [NSString stringWithFormat] provide a very low precision...

2) Printing via [NSNumber numberWithDouble] provides a better precision...

I would have expected to get a result much closer to the original value: 3.14159265358979323846264338327950288 (as defined in math.h)

Any clues?

解决方案

The first two lines round to 6 decimals because that's the default rounding length for printf inherited from C.

The third line displays the data with the maximum useful precision - an IEEE 754 64bit floating-point number has slightly less than 16 decimal digits of precision, so all those digits of the literal in math.h are pointless (perhaps they can be seen as future-proofing against a possible future redefinition in a format with more precision).

这篇关于如何在iOS上以全精度打印双精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:48