当前位置:网站首页>[deep anatomy of C language] storage principle of float variable in memory & comparison between pointer variable and "zero value"
[deep anatomy of C language] storage principle of float variable in memory & comparison between pointer variable and "zero value"
2022-06-30 13:07:00 【Muxixi】
I'm Muxi Xi
List of articles
- float Variable
- Pointer variables and “ Zero value ” Compare
- 🧵else With which if What about pairing ?
- At the end


float Variable
The storage principle of floating point numbers in memory
According to international standards IEEE( Institute of electrical and Electronic Engineering ) 754, Any binary floating point number V It can be expressed in the following form :
(-1)^S * M * 2^E
(-1)^S The sign bit , When S=0,V Is a positive number ; When S=1,V It's a negative number .
M Represents a significant number , Greater than or equal to 1, Less than 2.
2^E Indicates the index bit .
for example :
In decimal system 5.0 Convert to binary yes 101.0, amount to 1.01*2^2
( Binary 0.1 Express 1*2^(-1); 0.11 Express 1*2^(-1)+1*2^(-2))
that , According to the above V The format of , We can draw S=0,M=1.01,E=2.
Decimal -5.0, Written as binary is -101.0 , amount to -1.01×2^2 . that ,S=1,M=1.01,E=2.
V=9.5f=1001.1=(-1)^0*1.0011*2^3
amount to S=0;M=1.0011;E=3.
IEEE 754 Regulations
about 32 Floating point number of bits , The highest 1 Bits are sign bits s, And then 8 Bits are exponents E, The rest 23 Bits are significant numbers M.
Single precision floating point storage model :
about 64 Floating point number of bits , The highest 1 Bits are sign bits S, And then 11 Bits are exponents E, The rest 52 Bits are significant numbers M.
Double precision floating point storage model :
IEEE 754 For significant figures M And the index E, There are some special rules .
Significant figures M The provisions of the
As I said before , 1≤M<2 , namely M It can be written. 1.xxxxxx In the form of , among xxxxxx Represents the fractional part .
IEEE 754 Regulations , Keep it in the computer M when , By default, the first digit of this number is always 1, So it can be discarded , Save only the back xxxxxx part . For example preservation 1.01 When , Save only 01, Wait until you read , Put the first 1 Add . The purpose of this , It's saving 1 Significant digits . With 32 For example, a floating-point number , Leave to M Only 23 position , Will come first 1 After giving up , It's equivalent to being able to save 24 Significant digits .
Index E The provisions of the
Index E For an unsigned integer
It means , If E by 8 position , Its value range is 0~255; If E by 11 position , Its value range is 0~2047. In memory E The true value of must be added with an intermediate number , about 8 Bit E, The middle number is 127; about 11 Bit E, The middle number is 1023.
for example : V=0.5f;
(-1)^0*1.0*2^(-1) Save as 32 When floating-point numbers are in place , Must be saved as E+127–>126
Save as 64 When floating-point numbers are in place , Must be saved as E+1023–>1022 namely float–>E( True value )+127( In the middle )–> Stored value
namely double–>E( True value )+1023( In the middle )–> Stored value
then , Index E Fetching from memory can be further divided into three cases :
E Not all for 0 Or not all of them 1
Floating point numbers are represented by the following rules , The index E The calculated value of minus 127( or 1023), Get the real value , And then the significant number M Add the first 1.
E All for 0
When the exponent of a floating point number E be equal to 1-127( perhaps 1-1023) That's the true value ,
Significant figures M No more first 1, It's reduced to 0.xxxxxx Decimals of . This is to show that ±0, And close to 0 A very small number of .
E All for 1
When significant number M All for 0, Express ± infinity ( It depends on the sign bit s);
float Variables and " Zero value " Compare
Floating point numbers are stored in memory , Not what we think , Is fully stored , Convert to binary in decimal , There may be a loss of accuracy .
Pay attention to the loss here , Not blindly reduced , There may be more . When the floating-point number itself is stored , When the calculations are endless , Meeting “ rounding ” Or other strategies
//code1
#include <stdio.h>
int main()
{
double x = 3.6;
printf("%.50f\n", x);
return 0;
}

//code2
#include <stdio.h>
int main()
{
double x = 1.0;
double y = 0.1;
printf("%.50f\n", x - 0.9);
printf("%.50f\n", y);
if ((x - 0.9) == y)
{
printf("you can see me!\n");
}
else
{
printf("oops\n");
}
return 0;
}

Conclusion : Because of the loss of accuracy , Two floating-point numbers , Never use == Make an equality comparison .
Floating point numbers themselves have a loss of precision , As a result, the results may be slightly different .
Floating point comparisons should be range precision comparisons
Pseudo code one :
if((x-y) > - precision && (x-y) < precision ){
//TODO
}
Pseudo code - Concise Edition
if(fabs(x-y) < precision ){
//fabs Is the absolute value of a floating-point number
//TODO
}
Precision can be defined directly as ( Macro definition ) Or use system accuracy .
Macro definition precision
#define EPS 0.0000000000000001
#include<stdio.h>
#include<math.h>
int main()
{
double x = 1.0;
double y = 0.1;
if (fabs((x - 0.9) - y) < EPS)
{
printf("x==y");
}
else
{
printf("x!=y");
}
return 0;
}
Output results :
System accuracy
#include<float.h> // Use the following two precision , You need to include this header file
DBL_EPSILON //double Minimum precision
FLT_EPSILON //float Minimum precision
#include <stdio.h>
#include <math.h> // Must contain math.h, Otherwise you can't use fabs
#include <float.h> // Must contain , Otherwise, the system accuracy cannot be used
int main()
{
double x = 1.0;
double y = 0.1;
printf("%.50f\n", x - 0.9);
printf("%.50f\n", y);
if (fabs((x - 0.9) - y) < DBL_EPSILON)
{
// The raw data is a floating point number , We will use DBL_EPSILON
printf("x==y\n");
}
else
{
printf("x!=y\n");
}
return 0;
}

Two precision definitions
#define DBL_EPSILON 2.2204460492503131e-016 /* smallest such that 1.0+DBL_EPSILON !=1.0 */
#define FLT_EPSILON 1.192092896e-07F /* smallest such that 1.0+FLT_EPSILON !=1.0 */
XXX_EPSILON Is the minimum error , yes :XXX_EPSILON+n It's not equal to n The smallest positive number of .
EPSILON The translation of this word is ’ε’ It means , The math , Is a very small positive number .
🧨x And " Zero value " Compare
#include <stdio.h>
#include <math.h>
#include <float.h>
int main()
{
double x = 0.00000000000000000000001;
//if (fabs(x-0.0) < DBL_EPSILON){ // How to write it 1
//if (fabs(x) < DBL_EPSILON){ // How to write it 2
if (x > -DBL_EPSILON && x < DBL_EPSILON)
{
printf("x==y\n");
}
else
{
printf("x!=y\n");
}
return 0;
}

x > -DBL_EPSILON && x < DBL_EPSILON: Why not >= && <= Well ?
XXX_EPSILON Is the minimum error , yes :
XXX_EPSILON+n It's not equal to n The smallest positive number of .
XXX_EPSILON+n It's not equal to n The smallest positive number of : There are many numbers +n Can not be equal to n, however XXX_EPSILON The smallest is the smallest , however XXX_EPSILON Still a member of the cause of inequality .
let me put it another way :fabs(x) <= DBL_EPSILON( confirm x Whether it is 0 The logic of ), If =, Just explain x In itself , Has been able to arouse others and him ± The data itself has changed , This doesn't fit 0 The concept of .
fabs Library function

fabs Is a library function used to calculate the absolute value of a floating-point parameter , The header file is math.h.
Example
/* ABS.C: This program computes and displays * the absolute values of several numbers. */
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void main( void )
{
int ix = -4, iy;
long lx = -41567L, ly;
double dx = -3.141593, dy;
iy = abs( ix );
printf( "The absolute value of %d is %d\n", ix, iy);
ly = labs( lx );
printf( "The absolute value of %ld is %ld\n", lx, ly);
dy = fabs( dx );
printf( "The absolute value of %f is %f\n", dx, dy );
}
Output
The absolute value of -4 is 4
The absolute value of -41567 is 41567
The absolute value of -3.141593 is 3.141593
Pointer variables and “ Zero value ” Compare
#include<stdio.h>
int main()
{
printf("%d\n", 0);//0
printf("%d\n", '0');// character 0,ASCII Code value 48
printf("%d\n", '\0');// End of string '\0',ASCII Code value 0
printf("%d\n", NULL);//0
//#define NULL ((void *)0)
return 0;
}

True transformation :
character string A by “123456” convert to int type , In this case, the string A The number of bytes is 7, and int The type is 4 Bytes , To make a real transformation , We need to write algorithms , Use related library functions to convert .
Forced type conversion :
Do not change the data in memory , Only change the corresponding type .
for example :
float a = 3.14;//3.14 The type is double, Stored in float Forced type conversion is required in the type
//float a =(float)3.14;
int* p = NULL;// Defining pointers must be initialized at the same time , Otherwise, it is a wild pointer
//if(p==0); if(p!=0);// Not recommended
//if(p); if(!p);// Not recommended
if(NULL==p); if(NULL!=p);// recommend
🧵else With which if What about pairing ?
//code1
#include<stdio.h>
int main()
{
int x = 0;
int y = 1;
if (10 == x)
if (11 == y)
printf("hello\n");
else
printf("world!\n");
return 0;
}
No print results .
//code2
#include<stdio.h>
int main()
{
int x = 0;
int y = 1;
if (10 == x)
{
if (11 == y)
{
printf("hello\n");
}
}
else
{
printf("world!\n");
}
return 0;
}
Print the results :world!
Conclusion :else matching if Take the principle of proximity
At the end
Friends who think it's good can pay attention to , Like or collect ! Thank you for your support .
Yours ️ Praise is the source of my creative power
Your collection is the direction of my struggle
Your attention is my greatest support
Yours ️ Comments are a bright light for me to move forward
It's not easy to create , I hope you can support Xiaomu
边栏推荐
- 电机控制park变换公式推导
- Substrate 源码追新导读: 修复BEEFY的gossip引擎内存泄漏问题, 智能合约删除队列优化
- STM32 移植 RT-Thread 标准版的 FinSH 组件
- Development of unity script program
- ABAP toolbox v1.0 (with implementation ideas)
- How to handle ZABBIX server startup failure
- Hangzhou E-Commerce Research Institute: the official website (website) is the only form of private domain
- Basic syntax of unity script (4) - access to other game objects
- elementui中清除tinymce富文本缓存
- Tronapi wave field interface PHP version - interface document attached - package based on thinkphp5 - source code without encryption - can be opened in two - detailed guidance of the author - 11:49:56
猜你喜欢

After the market value evaporated by 65billion yuan, the "mask king" made steady medical treatment and focused on condoms

60 个神级 VS Code 插件!!

Idea 2021.3 golang error: rning: undefined behavior version of delve is too old for go version 1.18

【C语言深度解剖】float变量在内存中存储原理&&指针变量与“零值”比较

发生QQ大规模盗号事件,暴露出什么网络安全问题?
![[one day learning awk] array usage](/img/75/4333452142a3c7325e0712f3306985.png)
[one day learning awk] array usage

uniapp支付之APP微信支付unicloud版(附源码)

ABAP工具箱 V1.0(附实现思路)

【驚了】迅雷下載速度竟然比不上虛擬機中的下載速度

The independent station is Web3.0. The national "14th five year plan" requires enterprises to build digital websites!
随机推荐
Flinksql customizes udatf to implement topn
Machine learning notes - Introduction to autocorrelation and partial autocorrelation
Kubeedge's core philosophy
Resource realization applet opening wechat official small store tutorial
mqtt-ros模拟发布一个自定义消息类型
Js根据相同值将数组转换为二维数组
MySQL judges the calculation result and divides it by 100
Determining the subject area of data warehouse construction
JS method of changing two-dimensional array to one-dimensional array
[yitianxue awk] regular matching
2022-06-23 帆软部分公式及sql生成(月份、季度取数)
微信小程序报错:TypeError: Cannot read property ‘setData‘ of undefined
商品服务-平台属性
PG基础篇--逻辑结构管理(表继承、分区表)
Definition of variables and assignment of variables in MySQL
Common UI components
Dataworks synchronizes maxcomputer to sqlserver. Chinese characters become garbled. How can I solve it
Hangzhou E-Commerce Research Institute: the official website (website) is the only form of private domain
黑马笔记---常用日期API
Introduction to the novelty of substrat source code: indexing of call calls and fully completing the materialization of storage layer