I'm looking to retrieving the fractional part of a number. Ie. if i given the number 3.14. I need the output to be 0.14 or 14.
And I need to do this without the using the built-in functions round, floor or ceiling.
For a sneaky solution, you can use regular expressions to crop off everything before the dot:
(define (fraction-only num)
(string->number (regexp-replace #rx".*(\\..*)" (number->string num) "\\1")))
A simple solution(provided you can use truncate) is something like this:
(define (fract-part n)
(- n (truncate n)))
It will have the usual floating-point math rounding errors though, so (fract-part 3.14) returns 0.14000000000000012
Related
When I use the following code in Racket:
#lang racket
(define (sieve x)
(if (stream-empty? x) empty-stream
(stream-cons (stream-first x)
(sieve (stream-filter (λ(q)(not (zero? (modulo q (stream-first x)))))
(stream-rest x))))))
(define (in-primes)
(sieve (in-naturals 2)))
(define (nth-prime n)
(for/last ([i (in-range n)]
[j (in-primes)]) j))
The largest number for which I can effectively compute the nth prime is 1000. Is this a reasonable implementation of the sieve of Eratosthenes, or is there something I can do to significantly speed up the above?
No, it's not. It's a trial division algorithm, and an extremely inefficient and suboptimal one.
Each candidate here is tested by all its preceding primes, whereas just those not greater than its square root are enough. This translates to immense worsening of complexity. I expect it runs at ~ n2 at best, in n primes produced, instead of ~ n1.45 of an optimal trial division sieve, or ~ n1.1 of a proper sieve of Eratosthenes implementation.
The creation of filters should be postponed until a prime's square is seen among the candidates, to make it an optimal trial division algorithm.
You can greatly improve your code's performance with a minimal edit, following the principle of "do less, get done more": instead of calling stream-first at each step, don't. Just produce the intermediate streams in full, as they are:
(define (sieves x)
(if (stream-empty? x)
empty-stream
(stream-cons x ; <-- here
(sieves (stream-filter
(λ (q) (not (zero? (modulo q (stream-first x)))))
(stream-rest x))))))
Now sieves produces a stream of streams. In each interim stream, all the numbers in the initial prefix from the first value up to its square are prime by construction. Now we can stop early, and thus drastically reduce the number of the interim streams.
To actually produce the primes, take first element from each interim stream except the last interim stream, and from the last interim stream take all elements, from the first element up to its square (or the desired upper limit - below that square). This will have roughly the same overall time complexity as the optimal trial division (which, at each step, takes away not just the head element from the current interim stream, but the whole prefix up to the head's square, so the next filter starts from there).
To estimate the magnitude of n-th prime, you can use formula p_n < n * log(n*log(n)), for n > 6 (according to Wiipedia).
You can find stream-based SoE code here, though in Scheme, not Racket.
see also:
From Turner's sieve to Bird's -- Haskell gist
How do I define the sieve function for prime computation using higher–order functions?
I make simple factorial program in Clojure.
(defn fac [x y]
(if (= x 1) y (recur (- x 1) (* y x)))
)
(def fact [n] (fac n 1))
How can it be done faster? If it can be done some faster way.
You can find many fast factorial algorithms here: http://www.luschny.de/math/factorial/FastFactorialFunctions.htm
As commented above, Clojure is not the best language for that. Consider using C, C++, ForTran.
Be careful with the data structures that you use, because factorials grow really fast.
Here is my favorite:
(defn fact [n] (reduce *' (range 1 (inc n))))
The ' tells Clojure to use BigInteger transparently so as to avoid overflow.
With the help of your own fact function (or any other), we can define this extremely fast version:
(def fact* (mapv fact (cons 1 (range 1 21))))
This will give the right results for arguments in the range from 1 to 20 in constant time. Beyond that range, your version doesn't give correct results either (i.e. there's an integer overflow with (fact 21)).
EDIT: Here's an improved implementation that doesn't need another fact implementation, does not overflow and should be much faster during definition because it doesn't compute each entry in its lookup table from scratch:
(def fact (persistent! (reduce (fn [v n] (conj! v (*' (v n) (inc n))))
(transient [1])
(range 1000))))
EDIT 2: For a different fast solution, i.e. without building up a lookup table, it's probably best to use a library that's already highly optimized. Google's general utility library Guava includes a factorial implementation.
Add it to your project by adding this Leiningen dependency: [com.google.guava/guava "15.0"]. Then you need to (import com.google.common.math.BigIntegerMath) and can then call it with (BigIntegerMath/factorial n).
I'm working on an assignment involving Racket and I was hoping somebody could lead me into the right direction.
I must calculate the norm of a list without recursion or using a loop and without defining any helper functions.
Is this possible? The only thing that comes to mind is to somehow use the built-in map functions
(define (norm lst)
(apply + (map square lst)))
In Scheme, the function (map fn list0 [list1 .. listN]) comes with the restriction that the lists must have the same number of elements. Coming from Python, I'm missing the freedom of Python list comprehensions, which look a lot like map above, but without this restriction.
I'm tempted to implement an alternative "my-map", which allows for lists of differing size, iterating through the first N elements of all lists, where N is the length of the shortest list.
For example, let num be 10 and lst be (1 2 3). With my-map, I hope to write expressions like:
(my-map + (circular-list num) lst)))
And get:
(11 12 13)
I have an easier time reading this than the more conventional
(map + (lambda (arg) (+ num arg)) lst)
or
(map + (make-list (length lst) num) lst)
Two questions:
As a Scheme newbie, am I overlooked important reasons for the restriction on `map`?
Does something like `my-map` already exist in Scheme or in the SRFIs? I did take a look at srfi-42, but either it's not what I'm looking for, or it was, and it wasn't obvious.
First, note that map does allow empty lists, but of course if there's one empty list then all of them should be empty.
Second, have a look at the srfi-1 version of map -- it is specifically different from the R5RS version as follows:
This procedure is extended from its R5RS specification to allow the arguments to be of unequal length; it terminates when the shortest list runs out.
Third, most Scheme programmers would very much prefer
(map (lambda (arg) (+ num arg)) lst)
My guess is that Scheme is different from Python in a way that makes lambda expressions become more and more readable as you get used to the language.
And finally, there are some implementations that come with some form of a list comprehension. For example, in Racket you can write:
(for/list ([arg lst]) (+ num arg))
Finally taking the plunge to learn a Lisp dialect (Scheme), I have encountered two definitions of a list -
"Either the empty list or a pair whose cdr is a list".
"A collection of S-Expressions enclosed by parentheses".
Are these definitions equivalent?
They're as equivalent as {'a','b','c'} and "abc"
The former is the machine's logical representation of a list, the latter is how you represent it in your code.
And in scheme, you can pretty much treat everything as a list :) (Someone's going to downvote me for that, but I found it to be true when trying to think scheme-esque.)
I'm going to bring out my favourite dog-and-pony show!
(source: hedgee.com)
This corresponds to the following:
(let ((s5 (sqrt 5)))
(/ (- (expt (/ (1+ s5) 2) n)
(expt (/ (- 1 s5) 2) n)) s5))
The diagram illustrates your first statement (the empty-list object is denoted as a black box). The code snippet illustrates your second. :-)