c*****t 发帖数: 1879 | 1 I have a BSON file, when using bsondump, it is
{ "double" : "1234567890.12345", "array" : [ "123.45", "67890.1234" ] }
But when I tried to print the same double values using Java, they
were:
{
"double" : 1234567890.1234500408172607421875,
"array" : [
123.4500000000000028421709430404007434844970703125,
67890.123399999996763654053211212158203125
]
}
I knew these double values could be exactly represented, but I was
wondering if there are equivalent libraries in Java that "guess"
the scale of the value?
Obviously for JSON output, it is good to have a cleaner output. | o*********r 发帖数: 203 | 2 According to the IEEE Standard for Floating-Point Arithmetic (IEEE 754),
which is used by most of modern CPUs, .45 can't be exactly represented by:
floating_num = a0x(1/2)^(1) + a1x(1/2)^(2)+ ...
a0,a1,... = 0, or 1
So, .45 can't be stored exactly in binary format. Some numbers can be stored
exactly in binary:
0.5 = (1)x(1/2)
0.25 = (1)x(1/4)
0.125 = (1)x(1/8)
0.375 = (1)x(1/4) + (1)x(1/8) | c*****t 发帖数: 1879 | 3 I know this. However, it is entirely possible, for the sake of not
printing unnecessary digits, to have a smaller representation.
For example, for the same compiler, there is ONE representation of
0.45 in double. Thus, even though 0.45 cannot be exactly represented,
it is going to be the same as 0.450000000000125 at maximum precision.
In this case, we can just print 0.45.
Now, even for different compilers, if you use the same algorithm to
go from string to double and back, you would arrive to the same result.
My problem is finding the right function / library to do the task.
stored
【在 o*********r 的大作中提到】 : According to the IEEE Standard for Floating-Point Arithmetic (IEEE 754), : which is used by most of modern CPUs, .45 can't be exactly represented by: : floating_num = a0x(1/2)^(1) + a1x(1/2)^(2)+ ... : a0,a1,... = 0, or 1 : So, .45 can't be stored exactly in binary format. Some numbers can be stored : exactly in binary: : 0.5 = (1)x(1/2) : 0.25 = (1)x(1/4) : 0.125 = (1)x(1/8) : 0.375 = (1)x(1/4) + (1)x(1/8)
| d****n 发帖数: 1637 | 4 你的json原文是 string typed key and value
你的 java unmarshal 之后是从string to float
应该从开始就杜绝string everywhere
【在 c*****t 的大作中提到】 : I have a BSON file, when using bsondump, it is : { "double" : "1234567890.12345", "array" : [ "123.45", "67890.1234" ] } : But when I tried to print the same double values using Java, they : were: : { : "double" : 1234567890.1234500408172607421875, : "array" : [ : 123.4500000000000028421709430404007434844970703125, : 67890.123399999996763654053211212158203125 : ]
| c*****t 发帖数: 1879 | 5 Found the solution.
https://arxiv.org/pdf/1310.8121.pdf
Modified the code a bit and it worked really well:
java -cp . Test 1234.1234
1234.1234
java -cp . Test 0.001234
0.001234
double max:
1.7976931348623157e308
double min:
2.2250738585072014e-308 |
|