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

Iphone 如何在iOS上以全精度打印双面打印?,iphone,cocoa-touch,double,precision,nslog,Iphone,Cocoa Touch,Double,Precision,Nslog,测试用例: NSLog(@"%f", M_PI); NSLog(@"%@", [NSString stringWithFormat:@"%f", M_PI]); NSLog(@"%@", [NSNumber numberWithDouble:M_PI]); 结果: 3.141593 3.141593 3.141592653589793 结论: 1) 通过NSLog()或[NSString stringWithFormat]打印的精度非常低 2) 通过[NSNumber numberWithDo

测试用例:

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

3.141593
3.141593
3.141592653589793

结论:

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

2) 通过[NSNumber numberWithDouble]打印可提供更好的精度

我本来希望得到一个更接近原始值的结果:3.14159265358979323846264338327950288(如math.h中定义的)

有什么线索吗?

试试这个:

NSLog(@"%.20f", M_PI);

精度稍高一点

前两行取整为6位小数,因为这是从C继承的
printf
的默认取整长度


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

您应该使用长双精度,最大格式为20位。@.20Lg。 长双精度是80位浮点,因此不会得到比这更好的精度。 还要注意的是,从XCode 4.3.2开始,常数不是长双精度表示法,即使许多数字表示一个长双精度;-)

结果是:


试试这个,这是我的工作


NSLog(@“%@,[NSString stringWithFormat:@“%f”,距离])

谢谢,但这没用。结果是3.14159265358979311600,四舍五入错误(最后5个数字似乎是错误的)@Ariel:这是因为它们是将真值四舍五入到52个二进制数字,然后将结果转换回十进制的结果。谢谢,但这没有帮助。结果是3.141592653589793792,四舍五入错误(最后三个数字似乎是错误的)
NSLog(@"%@", [NSDecimalNumber numberWithDouble:M_PI]); 
NSLog(@"%.21g", M_PI);

// with cast because M_PI is not defined as long double
NSLog(@"%.21Lg", (long double)M_PI);

// with corrected long double representation (#.####L):
//                                   v from here on overhead 
NSLog(@"%.21Lg", 3.14159265358979323846264338327950288L);

// alternative for creating PI
NSLog(@"%.21Lg", asinl(1.0)*2.0);
// and a funny test case:
NSLog(@"%.21Lg", asinl(1.0)*2.0 - M_PI); // on second thought, not that funny: should be 0.0
p[5528:f803] 3.141592653589793116   (actually 16 digits standard double precision)
p[5528:f803] 3.141592653589793116
p[5528:f803] 3.14159265358979323851
p[5528:f803] 3.14159265358979323851
p[5575:f803] 1.22514845490862001043e-16 (should have been 0.0)