edem
edem

Reputation: 3272

Get a string instead of a number

This works fine:

[1]> ((lambda (x) (/ x x)) 5)
1

but this:

[2]> ((lambda (x y) (/ x y)) 5 2)
5/2

give me '5/2' instead of 2.5. How can I fix it?

Upvotes: 2

Views: 101

Answers (1)

Barmar
Barmar

Reputation: 780663

Common Lisp performs rational arithmetic whenever possible. If you want floating point, you either have to supplying at least one float as input to the arithmetic function, or use an explicit coercion function on the result.

((lambda (x y) (float (/ x y)) 5 2)

or

((lambda (x y) (/ x y)) 5.0 2)

Rational arithmetic is generally more exact than floating point. Consider this:

(setf x1 (/ 1 3)) => 1/3
(setf x2 (float (/ 1 3)) => 0.33333333
(* x1 3) => 1
(* x2 3) => 0.99999999

Upvotes: 8

Related Questions