Skip to content

Instantly share code, notes, and snippets.

@dyoo
Created September 22, 2012 06:13
Show Gist options
  • Save dyoo/3765326 to your computer and use it in GitHub Desktop.
Save dyoo/3765326 to your computer and use it in GitHub Desktop.
decimal to binary fraction
#lang racket/base
(require racket/stream)
;; decimal-to-binary-fraction: positive-real-less-than-1 -> (sequenceof (U 0 1))
;; Computes the binary expansion of the fraction part of a number.
(define (decimal-to-binary-fraction n)
(let loop ([n n]
[current-fraction 1/2])
(cond [(= n 0)
empty-stream]
[(>= n current-fraction)
(stream-cons 1
(loop (- n current-fraction)
(* 1/2 current-fraction)))]
[else
(stream-cons 0
(loop n (* 1/2 current-fraction)))])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment