[Tutor] Loop over floating point values

Amit Saha amitsaha.in at gmail.com
Sun Dec 8 07:18:59 CET 2013


On Mon, Dec 2, 2013 at 4:49 PM, eryksun <eryksun at gmail.com> wrote:
> 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

Thanks eryksun, that example taught me more than one thing there.

Best,
Amit.


-- 
http://echorand.me


More information about the Tutor mailing list