## newbie question: floating point addition operation

Discussion of Common Lisp

### newbie question: floating point addition operation

Can someone explain this:

Code: Select all
`CG-USER(9): (+ 2.32 0.001)2.3209999`

I have Allegro Common Lisp, 9.0, Windows 7 machine.

What is the proper way to correctly display 2.321 ?
hajovonta

Posts: 17
Joined: Wed Aug 24, 2011 12:42 am

### Re: newbie question: floating point addition operation

Since floating point numbers are represented internally as numbers by the base of two there isn't a way to represent 0.001 exactly. There will always be rounding errors. This isn't a problem of Lisp but of floating point arithmetic in general. The only way around it is to print it rounded:
Code: Select all
`(format t "~,5f" (+ 2.32 0.001))-> 2.32100`
Last edited by Konfusius on Tue Mar 05, 2013 5:23 am, edited 1 time in total.
Konfusius

Posts: 62
Joined: Fri Jun 10, 2011 6:38 am

### Re: newbie question: floating point addition operation

Thanks, that suits for me.
hajovonta

Posts: 17
Joined: Wed Aug 24, 2011 12:42 am

### Re: newbie question: floating point addition operation

Marco Antoniotti
marcoxa

Posts: 85
Joined: Thu Aug 14, 2008 6:31 pm

### Re: newbie question: floating point addition operation

Maybe it was my high expectations
hajovonta

Posts: 17
Joined: Wed Aug 24, 2011 12:42 am

### Re: newbie question: floating point addition operation

hajovonta wrote:Maybe it was my high expectations

If you want exact rationals, use exact rationals.

Code: Select all
`CL-USER> (+ 232/100 1/1000)2321/1000`

Kompottkin

Posts: 94
Joined: Mon Jul 21, 2008 7:26 am
Location: München, Germany

### Re: newbie question: floating point addition operation

ok, but then I want to display the result in floating point format...
hajovonta

Posts: 17
Joined: Wed Aug 24, 2011 12:42 am

### Re: newbie question: floating point addition operation

You can convert rationals to floats:
Code: Select all
`(float (+ 232/100 1/1000))-> 2.321`
Konfusius

Posts: 62
Joined: Fri Jun 10, 2011 6:38 am

### Re: newbie question: floating point addition operation

Konfusius wrote:You can convert rationals to floats:
Code: Select all
`(float (+ 232/100 1/1000))-> 2.321`

Technically, that (somewhat) reintroduces the problem...

Code: Select all
`L> (format t "~E" (float (+ 232/100 1/1000)))2.3210001e+0NILL> (= 2.3210001 (float (+ 232/100 1/1000)))T`

The Right Thing[TM] would be to use something like Wu-Decimal:

Code: Select all
`L> (ql:quickload "wu-decimal"); Loading "wu-decimal"[package wu-decimal]...("wu-decimal")L> (wu-decimal:enable-decimal-printing-for-ratios)NILL> (format t "~A" (+ 232/100 1/1000))2.321NIL`

Of course, I'm nitpicking. If you're just hacking something together to quickly visualize something, using floating point and rounding the results isn't so bad.

Kompottkin

Posts: 94
Joined: Mon Jul 21, 2008 7:26 am
Location: München, Germany