Storing numbers with higher precision in C

我们两清 提交于 2019-12-24 05:41:12

问题


I am writing a program in which I need to store numbers with a very high precision(around 10^-10) and then further use them a parameter( create_bloomfilter ([yet to decide the type] falsePositivity, long expected_num_of_elem) ).
The highest precision I am able to get is with double (something around 10^-6) which is not sufficient.

How can we store numbers with more higher precision in c?


回答1:


You have been misinformed about double.

The smallest positive number you can store in a double is about 2⨯10-308, not counting denormalized numbers, which can be smaller. Denormals go down to 5⨯10-324. They have the equivalent of about 15-17 digits of precision, which is sufficient to measure the diameter of the Earth to within the size of a red blood cell, the smallest cell in the human body.

If you really need more precision, you need MPFR. (If your algorithms are numerically unstable, MPFR might not help.)

Edit: I figured out what you are doing wrong.

In C, 10^-7 is an integer expression. It should be equal to -13 on most systems. The ^ operator is the bitwise XOR operator, not the exponentiation operator. There is no exponentiation operator in C, because C operators generally correspond to more primitive operations, at least in terms of hardware implementation.

You want 1e-7, or pow(10, -7).

#include <stdio.h>
#include <math.h>
int main(int argc, char *argv[])
{
    printf("2e-308 = %g\n", 2e-308);
    printf("2 * pow(10, -308) = %g\n", 2 * pow(10, -308));
    printf("10^-7 = %d\n", 10^-7);
    return 0;
}

Output:

2e-308 = 2e-308
2 * pow(10, -308) = 2e-308
10^-7 = -13

Note that there are a lot of gotchas with floating point numbers.




回答2:


Try GNU MPFR library and GNU GMP library

The MPFR library is a C library for multiple-precision floating-point computations with correct rounding.

GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on. GMP has a rich set of functions, and the functions have a regular interface.




回答3:


Is long double sufficient? Some implementations use 128bit long double, which should easily handle your requirements.

http://en.wikipedia.org/wiki/Quadruple_precision

If you're looking for something extremely strong, check out MPFR



来源:https://stackoverflow.com/questions/11114548/storing-numbers-with-higher-precision-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!