On Sat, 23 Jun 2007, hu ting wrote: > I have a problem about Scheme. When I do a loop in the meep just like this: > (do ((deg 30 (+ deg 0.2)))((> deg 40))(print deg "--")) > > the result is strange: > 30--30.2--30.4--30.6--30.8--31.0--31.2--31.4--31.6--31.8--32.0-- > 32.2--32.4--32.6--32.8--33.0--33.2--33.4--33.6--33.8--34.0--34.2-- > 34.4--34.6--34.8--35.0--35.2--35.4--35.6--35.8--36.0-- > 36.2000000000001--36.4000000000001--36.6000000000001-- > 36.8000000000001--37.0000000000001--37.2000000000001-- > 37.4000000000001--37.6000000000001--37.8000000000001--38.0000000000001-- > 38.2000000000001--38.4000000000001--38.6000000000001--38.8000000000001-- > 39.0000000000001--39.2000000000001--39.4000000000001--39.6000000000001-- > 39.8000000000001-- > > Why there so many 0000000000001 at the end? > and How can I avoid them?
This has nothing to do with Scheme -- exactly the same thing would happen in C, or any other language that uses standard floating-point arithmetic. The reason is that 0.2 is not exactly representable in binary floating-point, and because of this small rounding errors (in the 15th significant digit) accumulate when you add 0.2 repeatedly. If you don't want to print out all 15 decimal places, you can use the (round-dig num-dig number) function to round a number to num-dig decimal places. e.g. use (print (round-dig 3 deg) "--") to print deg to 3 decimal places. Steven _______________________________________________ meep-discuss mailing list [email protected] http://ab-initio.mit.edu/cgi-bin/mailman/listinfo/meep-discuss

