'浮动'与'双'精度 [英] 'float' vs. 'double' precision

查看:117
本文介绍了'浮动'与'双'精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码

  float x = 3.141592653589793238; 
double z = 3.141592653589793238;
printf(x =%f \ n,x);
printf(z =%f \ n,z);
printf(x =%20.18f\\\
,x);
printf(z =%20.18f\\\
,z);

会给你输出

  x = 3.141593 
z = 3.141593
x = 3.141592741012573242
z = 3.141592653589793116

第三行输出 741012573242 是垃圾,第四行 116 是垃圾。双打总是有16位有效数字,而花车总是有7位有效数字?为什么不双打有14位有效数字?

解决方案

浮点数在C中使用 IEEE 754 编码。

这种类型的编码使用符号,





$因为这个编码,许多数字将有小的变化,允许他们被存储。因为它是一个二进制表示,而不是十进制表示,所以有效位的数目可以稍微改变。

单精度(float)给你23位8位指数和1个符号位。

双精度(double)给出52位有效位,11位指数和1位符号位。

The code

float x  = 3.141592653589793238;
double z = 3.141592653589793238;
printf("x=%f\n", x);
printf("z=%f\n", z);
printf("x=%20.18f\n", x);
printf("z=%20.18f\n", z);

will give you the output

x=3.141593
z=3.141593
x=3.141592741012573242
z=3.141592653589793116

where on the third line of output 741012573242 is garbage and on the fourth line 116 is garbage. Do doubles always have 16 significant figures while floats always have 7 significant figures? Why don't doubles have 14 significant figures?

解决方案

Floating point numbers in C use IEEE 754 encoding.

This type of encoding uses a sign, a significand, and an exponent.

Because of this encoding, many numbers will have small changes to allow them to be stored.

Also, the number of significant digits can change slightly since it is a binary representation, not a decimal one.

Single precision (float) gives you 23 bits of significand, 8 bits of exponent, and 1 sign bit.

Double precision (double) gives you 52 bits of significand, 11 bits of exponent, and 1 sign bit.

这篇关于'浮动'与'双'精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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