[racket] (floor (/ ....))

From: Stephan Houben (stephanh42 at gmail.com)
Date: Tue Jun 11 03:45:33 EDT 2013

Hi Brad,

First of all, I would advocate modulo, not quotient.
Then at least it also works correctly for negative integers.

Secondly, I see the code out of context, but variable names like "weight"
and "volume"
to me suggest that they may be arbitrary (non-negative) real numbers.
And then modulo doesn't work.

So for posterity, if you know a and b are integers:
  replace (floor (/ a b)) with (modulo a b)
  replace (truncate (/ a b)) with (quotient a b)

2013/6/10 Bradley Lucier <lucier at math.purdue.edu>

> Re:
>> FWIW, I would have at least written:
>>         ((qty (in-range 0 (add1 (min (floor (/ weight-left weight))
>>                                      (floor (/ volume-left volume)))))))
> I have now seen the
> (floor (/ a b))
> idiom a number of times, and wonder why people prefer it to
> (quotient a b)
> Normally, to calculate (/ a b) where a and b are exact integers requires
> one to calculate (gcd a b) to put the fraction into lowest terms
> p/q=(quotient a (gcd a b))/(quotient b (gcd a b)); then, to calculate
> (floor p/q), one must calculate (quotient p q).
> For large integers of size  $N$ bits, (gcd a b) takes $O(N\log^2(N))$
> fixnum operations, where quotient takes $O(N\log N)$ operations.  This
> assumes Fourier-based methods for bignum multiplication; for more direct
> methods, the difference in operation count is larger.
> In any case, the (floor (/ ...)) idiom takes noticeably more time than
> (quotient ...).  If one knows that a and b are positive integers, they give
> the same results.
> This is an argument not to use (floor (/ ...)).  Are there arguments in
> favor of this idiom?
> Brad
> ____________________
>  Racket Users list:
>  http://lists.racket-lang.org/**users <http://lists.racket-lang.org/users>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20130611/f0e83811/attachment.html>

Posted on the users mailing list.