On Wed, Dec 21, 2011 at 12:24:09PM -0800, Michael R wrote:
> main() {
> ??? int x;
> ??? x
> =???? ( .00425 * 2 ) + .0025;
> ???
> printf ( "%24.24f\n", x - ( .00425 * 2) - .0025);
>
> }
>
> mikeraz@hive:~> gcc fp.c -o fp
> mikeraz@hive:~> ./fp
> -0.011000000000000001096345
Shouldn't that be something like double x; or float x; ???
-----------------------------------------------------------------
#include <stdio.h>
main() {
double x = (.00425 * 2 ) + .0025 ;
printf ( "%24.24f\n", x - ( .00425 * 2) - .0025);
}
[keithl@kao ~]$ gcc -o fp fp.c
[keithl@kao ~]$ ./fp
0.000000000000000000433681
-----------------------------------------------------------------
... if we declare a float instead of double :
[keithl@kao ~]$ ./fp
-0.000000000059604645438055
-----------------------------------------------------------------
... for somewhat better precision ( I'm too lazy to count zeros):
main() {
#include <stdio.h>
long double x = (.00425 * 2 ) + .0025 ;
printf( "%16.8le\n", x - ( .00425 * 2) - .0025 );
}
[keithl@kao ~]$ ./fp
-0.00000000e+00
-----------------------------------------------------------------
But why stop there? We can use GMP, the Gnu Multiple Precision
Library, and compute something a wee bit more challenging:
kpm.c -----------------------------------------------------------
// use gmp, http://libgmp.org
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
int main(void)
{
mpf_set_default_prec (4000000); // yes, 4 million bits
mpf_t x;
mpf_t y ;
mpf_t result;
mpf_init(x);
mpf_init(y);
mpf_init(result);
mpf_set_str(x, "1e1000000", 10);
mpf_set_str(y, "1e0", 10);
mpf_add(result, x, y);
gmp_printf("after add: %Fe\n", result);
mpf_sub(y, result, x);
gmp_printf("after subtract: %Fe\n", y );
}
--------------------------
compile and run it:
[keithl@kao ~]$ gcc -o fpm fpm.c -lgmp ; ./fpm
after add: 1.000000e+1000000
after subtract: 1.000000e+00
A million decimal places seems like adequate precision.
Something segfaults if I try 10 million decimal places,
which is sad, because I would like to compute a number
that would take more than a lifetime to read ...
It might be amusing to compute cos(1e1000000)+cos(1e1000000+pi)
and see how well the GMP trig routines work. You can spend
a few hours melting your CPU instead of mine.
And yes, I sometimes use libgmp for real, doing 128 bit
precision (and incredibly time consuming) orbital
calculations, where the roundoff error of long doubles
is a bit too much. Don't YOU want to know where YOUR
satellite is, within a few nanometers, so you can look
at relativistic frame drag?
Keith
--
Keith Lofstrom [email protected] Voice (503)-520-1993
KLIC --- Keith Lofstrom Integrated Circuits --- "Your Ideas in Silicon"
Design Contracting in Bipolar and CMOS - Analog, Digital, and Scan ICs
_______________________________________________
PLUG mailing list
[email protected]
http://lists.pdxlinux.org/mailman/listinfo/plug