Path: utzoo!mnetor!uunet!lll-winken!lll-tis!ames!killer!codas!mtune!mtunx!whuts!mhuxh!mhuxt!mhuxu!mhuxi!mhuxd!mhuxm!gak From: gak@mhuxm.UUCP (Vincent Hatem) Newsgroups: comp.lang.c Subject: Re: How not to write a loop Message-ID: <724@mhuxm.UUCP> Date: 4 Mar 88 22:38:28 GMT References: <296@draken.nada.kth.se> <64400004@convex> Organization: AT&T Bell Laboratories, Murray Hill Lines: 35 Summary: you didn't study in college In article <64400004@convex>, authorplaceholder@convex.UUCP writes: >> In article <832@unmvax.unm.edu>, mike@turing.UNM.EDU (Michael I. Bushnell) writes: > [lots of junk I've deleted...] > >> I just tried the very similar loop >> for (x = 0; x < 21; x += .3) /* .3 divides 21 exactly */ >> By analogy with your "of course", the last output should obviously >> be 20.7. In fact, when I tried it just now, the last output was >> 20.999994 > > more float-double round off error. This kind of thing bites you when you > use the -lm libraries without #including . > > The opinions stated above are barely my own, how can they be of my employers? > Mike Cuddy, > CONVEX Computer Corporation The errors are caused by the inherent nature of ANY IEEE floating point number. Try it with 0.1 as an increment. It's even worse. It's all because you simply *can't* represent the number 0.1 with IEEE floating point. You can come very, *very*, close - but you'll still have something like 0.099999999999999 instead of 0.10000000000... This occurs in *both* 32 and 64 bit floating point numbers, and is called "rounding errors." The 64 bit numbers are more accurate, but they are still off. When you printf() a floating point number, the function *rounds* the float, then prints it. Take a numerical methods course. -- Vincent Hatem AT&T International, International Systems Operations, UNIX Technical Support Telefon: (201) 953-8030 Please send all e-mail to: ihnp4!atti01!vch