"arithmetic" change between 1.0.0 and 1.1. 0

1 view
Skip to first unread message

prhlava

unread,
Nov 16, 2009, 5:56:28 AM11/16/09
to Clojure

Hello,

I was testing if my code works with Clojure 1.1.0-alpha-SNAPSHOT - the
full code is attached to this group (in files section) as parallel-
factorial*.clj .

The code works in 1.0.0, but blows up in 1.1.0 for bigger numbers.
After a bit of digging, I found that following function is the culprit
(working version shown):

;----------------------
(defn part-num [#^Integer n #^Integer m]
(let [z (int (Math/floor (/ n m))) ; it generates float ranges
without the cast to int
last-range (range (+ (* z m) 1) (+ n 1))
]
(println z)
(println last-range)
(cons (if last-range last-range '(1))
(for [x (range m)]
(range (+ (* x z) 1) (+ (* (+ x 1) z) 1))
)
)
)
)
;----------------------

The problem is that without casting "z" to integer, the generated list
of ranges will have float numbers (and not integers), and that will
over-flow to infinity for large numbers when used in pfactorial
function.

No big deal, the fix is simple - this is heads up if more people find
their code broke with over-flow to infinity with the new version of
clojure.

It looks that float type "propagates" into arithmetics (and it did not
before) - better explanation welcome.

Kind regards,

Vladimir

Stephen C. Gilardi

unread,
Nov 25, 2009, 1:48:18 AM11/25/09
to clo...@googlegroups.com

On Nov 16, 2009, at 5:56 AM, prhlava wrote:

> No big deal, the fix is simple - this is heads up if more people find
> their code broke with over-flow to infinity with the new version of
> clojure.
>
> It looks that float type "propagates" into arithmetics (and it did not
> before) - better explanation welcome.

I think your analysis is likely correct. Certainly Math/floor does return a Double and Clojure's number handling has evolved over time.

As an alternative to the code you posted, for positive integers n and m,

(int (Math/floor (/ n m))

is equivalent to

(quot n m)

If negative values are possible, you could write a function based on quot that would give the appropriate answer in all cases.

--Steve

prhlava

unread,
Nov 30, 2009, 1:25:25 PM11/30/09
to Clojure

Hello Steve,

> As an alternative to the code you posted, for positive integers n and m,
>         (int (Math/floor (/ n m))
> is equivalent to
>         (quot n m)
> If negative values are possible, you could write a function based on quot that would give the appropriate answer in all cases.

Thank you, this makes sense + makes the code simpler :-) (as negative
values would be "wrong" in this particular case).

Kind regards,

Vlado
Reply all
Reply to author
Forward
0 new messages