How to convert real to exact integer in Racket?
Asked Answered
S

2

13

How do I convert a value of the form 20.2 into something that (random ...) accepts?

I've tried these:

;; x defined by some earlier maths and of form 20.2

(random (round x))
(random (floor x))

But both return:

random: contract violation
expected: (or/c (integer-in 1 4294967087) pseudo-random-generator?)
given: 20.0
Southeastwardly answered 13/2, 2016 at 14:22 Comment(0)
M
17

These also work, and according to the documentation they're just shorthands for your approach:

(random (exact-round x))
(random (exact-floor x))
Murmur answered 13/2, 2016 at 14:39 Comment(0)
S
5

This article seems to answer the question for Scheme: http://computer-programming-forum.com/40-scheme/674db7a1706960d5.htm

So with code like this I get the result I want:

(random (inexact->exact (round x)))
(random (inexact->exact (floor x)))

Is this the simplest way?

Southeastwardly answered 13/2, 2016 at 14:23 Comment(1)
In racket, the exact-round and exact-floor functions from racket/math do that.Memo

© 2022 - 2024 — McMap. All rights reserved.