# PostgreSQL 源码解读（196）- 浮点数比较

testdb=# select 123.31::double precision > 123.45::double precision;;

### 二、源码解读

/*
*      float8{eq,ne,lt,le,gt,ge}       - float8/float8 comparison operations
*/
int
float8_cmp_internal(float8 a, float8 b)
{
/*
* We consider all NANs to be equal and larger than any non-NAN. This is
* somewhat arbitrary; the important thing is to have a consistent sort
* order.
*/
if (isnan(a))
{
if (isnan(b))
return 0;           /* NAN = NAN */
else
return 1;           /* NAN > non-NAN */
}
else if (isnan(b))
{
return -1;              /* non-NAN < NAN */
}
else
{
if (a > b)//a > b,返回1
return 1;
else if (a < b)//a < b,返回-1
return -1;
else
return 0;//否则,返回0
}
}

### 三、跟踪分析

testdb=# select 123.31::double precision > 123.45::double precision;

(gdb) c
Continuing.
Breakpoint 1, float8_cmp_internal (a=123.31, b=123.45) at float.c:1056
1056        if (isnan(a))

(gdb) x/8b &a
0x7ffcd2cac728: 0xa4    0x70    0x3d    0x0a    0xd7    0xd3    0x5e    0x40
(gdb) x/8b &b
0x7ffcd2cac720: 0xcd    0xcc    0xcc    0xcc    0xcc    0xdc    0x5e    0x40
(gdb)

[xdb@localhost source]\$ cat double_test.c
#include <stdio.h>
int main() {
double d1 = 123.31;
double d2 = 123.45;
printf("d1 : %llx \n", *((long *)&d1));
printf("d2 : %llx \n", *((long *)&d2));
}
[xdb@localhost source]\$ gcc double_test.c -o dt
[xdb@localhost source]\$ ./dt
d1 : 405ed3d70a3d70a4
d2 : 405edccccccccccd

DONE!

• 博文量
1274
• 访问量
3749847