[Tutor] Loop over floating point values
eryksun
eryksun at gmail.com
Mon Dec 2 07:49:20 CET 2013
On Mon, Dec 2, 2013 at 1:28 AM, Amit Saha <amitsaha.in at gmail.com> wrote:
> Indeed, that's a good point. Surprisingly, C does it just fine:
>
> # include <stdio.h>
>
> int main(int argc, char **argv)
> {
> float x = 0.0;
> while(x<1)
> {
> x += 0.1;
> printf("%f\n", x);
> }
>
> return 0;
> }
Python uses double precision:
>>> import os, ctypes
>>> open('tmp.c', 'w').write(r'''
... double test_d() {
... double x = 0.0;
... while (x < 1.0)
... x += 0.1;
... return x;
... }
... float test_f() {
... float x = 0.0;
... while (x < 1.0)
... x += 0.1;
... return x;
... }
... ''')
>>> rc = os.system('gcc -shared -o tmp.so tmp.c')
>>> tmp = ctypes.CDLL('./tmp.so')
>>> tmp.test_d.restype = ctypes.c_double
>>> tmp.test_f.restype = ctypes.c_float
>>> tmp.test_d()
1.0999999999999999
>>> tmp.test_f()
1.0000001192092896
More information about the Tutor
mailing list