Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!wuarchive!uwm.edu!lll-winken!tristan!loren From: loren@tristan.llnl.gov (Loren Petrich) Newsgroups: comp.lang.c Subject: Re: Inherent imprecision of floating point variables Message-ID: <64734@lll-winken.LLNL.GOV> Date: 14 Jul 90 01:08:51 GMT References: <3300@crash.cts.com> <44436@ism780c.isc.com> Sender: usenet@lll-winken.LLNL.GOV Reply-To: loren@tristan.UUCP (Loren Petrich) Organization: Lawrence Livermore National Laboratory Lines: 48 In article dylan@ibmpcug.CO.UK (Matthew Farwell) writes: >In article <44436@ism780c.isc.com> marv@ism780.UUCP (Marvin Rubenstein) writes: >Consider the code segment:- > >main() >{ > float f; > > f = 0.0; > while (1) { > if (f == 10.0) break; > printf("%f\n", f); > f += 0.1; > } > printf("Stopped\n"); >} > >If its all to do with conversion routines, why doesn't this stop when f >reaches 10? That is because 0.1 is not represented as a finite-length number in binary. In binary form it is: 0.0011001100110011... with an infinitely repeating sequence of digits. Check it out by multiplying it by 10 (binary: 1010). Since a computer will only use finite-length numbers, it will cut off this infinite-length representation, and get a number that is not quite 0.1. But no integer multiple of that can equal 10.0, so the program gets stuck in an infinite loop. The moral: avoid this sort of test. You won't get exact agreement. ^ Loren Petrich, the Master Blaster \ ^ / loren@sunlight.llnl.gov \ ^ / One may need to route through any of: \^/ <<<<<<<<+>>>>>>>> lll-lcc.llnl.gov /v\ lll-crg.llnl.gov / v \ star.stanford.edu / v \ v For example, use: loren%sunlight.llnl.gov@star.stanford.edu My sister is a Communist for Reagan