Fixed precision in C

c, precision

Solution

I would recommend `GNU MPFR` library for precise floating-point computation. `GMP` is very robust and specialized in large integers (`mpz`, `mpq` or internal `mpn` categories), however they recommed this library for multi-precision floating-point, even directly on their main site:

New projects should strongly consider using the much more complete GMP extension library mpfr instead of mpf.

Problem

Can C language handle user-set precision calculations? I know that float and double type won't do the job, nor do exist some fixed-precision variable types, like I've seen in Java or in C#. I'm asking so because I'm writing a program that implements an algorithm which calculates an approximation of y=log x, which needs to do fixed-precision arithmetic both to terminate and to give a correct approximation of the logarithm. My program terminates, since float has however a maximum precision, but the answer contains more error than when I try the algorithm with pencil and paper. For instance, once x has been specified, the program first does this declaration: ``` float z = floor(x*pow(a, p-1) + offset)/pow(a,p); ``` where a is an integer, for example 10, and p is another integer, the precision number, for example 3. I discovered with GDB that, if we assume that x=4, z is not 0.4, as it should be, but it's actually 0.400000006 I know that this is the normal behaviour of floats and doubles, but in this specific program I need to specify the exact number of digits after the radix point, that is p, as written above. In fact, when the program terminates, the logarithm of x is calculated with the intrinsic error of the algorithm, plus the error given by floating-point arithmetic every time there is a calculation similar to the one above. So, is there a way I can manually set the precision of the variables so as to improve the accuracy of the final result?

Original source