Absolute value of a number in Clojure - clojure

How can the absolute number of a value be calculated in Clojure?
(abs 1) => 1
(abs -1) => 1
(abs 0) => 0

As of Clojure 1.11, it is simply (abs -1) in both Clojure and Clojurescript.
In versions before, for double, float, long and int you can use the java.lang.Math method abs (Math/abs -1)
Take care it won't work for decimals, ratio's, bigint(eger)s and other Clojure numeric types. The official clojure contrib math library that tries guarantee working correctly with all of these is clojure.math.numeric-tower

you could always do
(defn abs [n] (max n (- n)))

The deprecated clojure.contrib.math provides an abs function.
The source is:
(defn abs "(abs n) is the absolute value of n" [n]
(cond
(not (number? n)) (throw (IllegalArgumentException.
"abs requires a number"))
(neg? n) (- n)
:else n))
As #NielsK points out in the comments, clojure.math.numeric-tower is the successor project.

abs is now available in the core clojure library since Clojure 1.11 release.
Docs for abs https://clojure.github.io/clojure/branch-master/clojure.core-api.html#clojure.core/abs
Usage: (abs a)
Returns the absolute value of a.
If a is Long/MIN_VALUE => Long/MIN_VALUE
If a is a double and zero => +0.0
If a is a double and ##Inf or ##-Inf => ##Inf
If a is a double and ##NaN => ##NaN
Added in Clojure version 1.11

Related

clojure: Compute Factorial of number using defmulti and defmethod

I tried to compute factorial through defmulti and defmethod.
(defmulti factorial identity)
(defmethod factorial 0 [_] 1)
(defmethod factorial :default [num]
(* num (factorial (dec num))))
It works fine for small numbers
(-> 10 factorial) ;;3628800
(-> 2 factorial) ;; 2
it shows Integer Overflow Exception for factorial 40
(-> 40 factorial)
ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow
My curiosity is
How can we compute factorial for Big Numbers using defmulti and defmethod?
Clojure's implementation of number types builds on the host platform's number types. Your solution works when you define the arbitrary size flag N, because the underlying number type changes on the JVM.
(type 10) ;=> java.lang.Long
(type 10N) ;=> clojure.lang.BigInt
clojure.lang.BigInt uses either java.math.BigInteger or a Java long as the underlying type, depending on the bit size of the number.
On a different host, the Javascript engine of a browser, both types are JavaScript's native Numbers. The factorial function gives a result up to 170 in ClojureScript. It does not throw when overflowing, but returns the JavaScript number value Infinity:
(factorial 170) ; => 7.257415615307994e+306
(factorial 170N) ; => 7.257415615307994e+306
(factorial 171N) ; => Infinity
Update: This answer (pointed out by #cske) gives a neat solution to use the *' operator, which bumps up the number type in case it would overflow:
(defmethod factorial :default [num]
(*' num (factorial (dec num))))
(factorial 40) ; => 815915283247897734345611269596115894272000000000N
I have solved it
(-> 40N factorial) ;;815915283247897734345611269596115894272000000000N

How to check whether a number is Fibonacci number in Clojure?

Input: a positive integer.
Output: true / false based on test.
Here is my attempt:
(defn is-a-fib? [x]
"Check whether x is a fibonacci number.
Algorithm: test whether 5x^2+4 or 5x^2-4 is a perfect square."
(let [a (+' (*' (Math/pow x 2) 5) 4) ; 5x^2+4
b (-' (*' (Math/pow x 2) 5) 4) ; 5x^2-4
sqrt-a (Math/sqrt a)
sqrt-b (Math/sqrt b)]
(or (== (*' sqrt-a sqrt-a)
(*' (Math/floor sqrt-a) (Math/floor sqrt-a))) ; Test whether n is a perfect square
(== (*' sqrt-b sqrt-b)
(*' (Math/floor sqrt-b) (Math/floor sqrt-b))))))
The problem is: this code doesn't work for a large number. I think it may cause stack overflow.
Is there a better way?
The Math/pow, Math/sqrt, and Math/floor operations work on doubles which have a limited range of precision, and operations on them will have rounding errors.
If you look at it in this light, things may derail simply owing to rounding, but they will really go wrong when you've exhausted the precision (15–17 decimal digits).
This first nth Fibonnacci where this algorithm gives a false positive for the subsequent integer is for the 16-digit integer associated with n = 74.
(is-a-fib? 1304969544928657)
=> true
(is-a-fib? 1304969544928658)
=> true
Edit: Adding arbitrary precision solution that avoids doubles:
The main difficulty is the lack of an integer square root algorithm.
This Java implementation can be translated to Clojure:
(defn integer-sqrt [n]
(let [n (biginteger n)]
(loop [a BigInteger/ONE
b (-> n (.shiftRight 5) (.add (biginteger 8)))]
(if (>= (.compareTo b a) 0)
(let [mid (-> a (.add b) (.shiftRight 1))]
(if (pos? (-> mid (.multiply mid) (.compareTo n)))
(recur a (.subtract mid BigInteger/ONE))
(recur (.add mid BigInteger/ONE) b)))
(dec a)))))
With that in place, you can define an arbitrary-precision perfect square test:
(defn perfect-square? [n]
(let [x (integer-sqrt n)]
(= (*' x x) n)))
And update your implementation to use it:
(defn is-a-fib? [x]
"Check whether x is a fibonacci number.
Algorithm: test whether 5x^2+4 or 5x^2-4 is a perfect square."
(let [a (+' (*' (*' x x) 5) 4) ; 5x^2+4
b (-' (*' (*' x x) 5) 4)] ; 5x^2-4
(or (perfect-square? a)
(perfect-square? b))))

implement in Clojure integer? in scheme

I'm new to Clojure, and can't find an equivalent of integer? in Chez scheme 8.4, mainly for test cases as below:
(integer? 39.0)
=> #t
The function I've come up so far is:
(defn actual-integer? [x] (or (= 0.0 (- x (int x))) (integer? x)))
Does it work when x is arbitrary number types or is there a better solution?
Thanks.
Well, strictly speaking 39.0 isn't an integer literal because it has the .0 part at the end. A simple implementation of the procedure would be:
(defn actual-integer? [x] (== (int x) x))
Notice that the == operator:
Returns non-nil if nums all have the equivalent value (type-independent), otherwise false

Clojure integer overflow

I'm running Clojure 1.4.0. Why is it if I add Integer/MAX_VALUE and 1, I get a Long, but if I add Integer/MAX_VALUE to itself, I get an exception?
=> (def one 1)
=> (class one)
java.lang.Integer
=> (def max-plus-one (+ Integer/MAX_VALUE one))
=> max-plus-one
2147483648
=> (class max-plus-one)
java.lang.Long
=> (+ Integer/MAX_VALUE Integer/MAX_VALUE)
java.lang.ArithmeticException: integer overflow (NO_SOURCE_FILE:0)
Shouldn't they both act the same way? Why does adding two MAX_VALUE values overflows but adding 1 doesn't?
I've seen this SO question but they are getting different behaviour than I am.
That's strange, I see different results with Clojure 1.4.0and Java(TM) SE Runtime Environment (build 1.7.0_06-b24), on Ubuntu 12.04 64bit:
user=> *clojure-version*
{:major 1, :minor 4, :incremental 0, :qualifier nil}
user=> (+ Integer/MAX_VALUE Integer/MAX_VALUE)
4294967294
user=> (type 1)
java.lang.Long
user=> (def max-plus-one (+ Integer/MAX_VALUE one))
#'user/max-plus-one
user=> max-plus-one
2147483648
user=> (type max-plus-one)
java.lang.Long
user=> (+ Integer/MAX_VALUE Integer/MAX_VALUE)
4294967294
You can always check the Java classes which clojure.core uses for numerics, to see how the functionality is implemented:
The implementation of the + operator in:
(defn +
"Returns the sum of nums. (+) returns 0. Does not auto-promote
longs, will throw on overflow. See also: +'"
{:inline (nary-inline 'add 'unchecked_add)
:inline-arities >1?
:added "1.2"}
([] 0)
([x] (cast Number x))
([x y] (. clojure.lang.Numbers (add x y)))
([x y & more]
(reduce1 + (+ x y) more)))
Java implementation of adding longs:
final public Number add(Number x, Number y){
return num(Numbers.add(x.longValue(),y.longValue()));
}
Edits: Tested with Clojure 1.2.1
I have done a quick test with Clojure 1.2.1, and with that version of Clojure I get exactly your behavior.
user=> *clojure-version*
{:major 1, :minor 2, :incremental 1, :qualifier ""}
user=> (def one 1)
#'user/one
user=> (class 1)
java.lang.Integer
user=> (def max-plus-one (+ Integer/MAX_VALUE one))
#'user/max-plus-one
user=> max-plus-one
2147483648
user=> (class max-plus-one)
java.lang.Long
user=> (+ Integer/MAX_VALUE Integer/MAX_VALUE)
java.lang.ArithmeticException: integer overflow (NO_SOURCE_FILE:0)
I'd say that you did the test with Clojure 1.2.x, and not with 1.4.0. What is the value of *clojure-version* in your REPL?
Looks like you have your answer, but here are a few other interesting points:
java (all versions) and clojure's (>1.3.0) default behaviour differ in their behaviour wrt overflow
in java
(Long.MAX_VALUE + 1) == Long.MIN_VALUE
(Integer.MAX_VALUE + 1) == Integer.MIN_VALUE
// cast required to avoid promoting to int
(Byte.MAX_VALUE + (byte)1) == Byte.MIN_VALUE
This is because arithmetic wraps by default on the jvm
in clojure (>1.3.0)
(inc Long.MAX_VALUE)
=> ArithmeticOverflow
(inc Integer/MAX_VALUE)
=> a long with value Integer/MAX_VALUE + 1
(int (inc Integer/MAX_VALUE))
=> IllegalArgumentException Value
out of range for int: 2147483648
clojure does have versions of some ops that behave like java
(unchecked-inc Long.MAX_VALUE) => Long.MIN_VALUE
You can make the unchecked operations the default by setting *unchecked-math* to true
(set! *unchecked-math* true)
(inc Long/MAX_VALUE)
=> (Long.MIN_VALUE)
(int (inc Integer/MAX_VALUE))
=> (Integer.MIN_VALUE) of type Integer
There are lots of other interesting (unchecked-*) operations.
As of version 1.3.0 Clojure uses Longs for all primitive numbers. you just need to use larger numbers to get the overflow.
(def max-plus-one (+ Long/MAX_VALUE one))

Why isn't this running in constant space (and how do I make it so it does)?

I'm doing Project Euler to learn Clojure.
The purpose of this function is to calculate the lcm of the set of integers from 1 to m.
(lcm 10) returns 2520
This is a rather brute-force way of doing this. In theory, we go through each number from m to infinity and return the first number for which all values 1 through m divide that number evenly.
If I understand what 'lazy' means correctly (and if I am truly being lazy here), then this should run in constant space. There's no need to hold more than the list of numbers from 1 to m and 1 value from the infinite set of numbers that we're looping through.
I am, however, getting a java.lang.OutOfMemoryError: Java heap space at m values greater than 17.
(defn lcm [m]
(let [xs (range 1 (+ m 1))]
(first (for [x (iterate inc m) :when
(empty?
(filter (fn [y] (not (factor-of? y x))) xs))] x))))
Thanks!
As far as I can tell, your code is in fact lazy (also in the sense that it's in no hurry to reach the answer... ;-) -- see below), however it generates piles upon piles upon piles of garbage. Just consider that (lvm 17) amounts to asking for over 1.2 million lazy filtering operations on (range 1 18). I can't reproduce your out-of-memory problem, but I'd tentatively conjecture it might be an issue with your memory & GC settings.
Now although I realise that your question is not actually about algorithms, note that the production of all that garbage, the carrying out of all those filtering operations etc. not only utterly destroy the space complexity of this, but the time complexity as well. Why not use an actual LCM algorithm? Like the one exploiting lcm(X) = gcd(X) / product(X) for X a set of natural numbers. The GCD can be calculated with Euclid's algorithm.
(defn gcd
([x y]
(cond (zero? x) y
(< y x) (recur y x)
:else (recur x (rem y x))))
([x y & zs]
(reduce gcd (gcd x y) zs)))
(defn lcm
([x y] (/ (* x y) (gcd x y)))
([x y & zs]
(reduce lcm (lcm x y) zs)))
With the above in place, (apply lcm (range 1 18)) will give you your answer in short order.
I'm getting the same OutOfMemoryError on Clojure 1.1, but not on 1.2.
I imagine it's a bug in 1.1 where for holds on to more garbage than necessary.
So I suppose the fix is to upgrade Clojure. Or to use Michal's algorithm for an answer in a fraction of the time.
While I accept that this is acknowledged to be brute force, I shiver at the idea. For the set of consecutive numbers that runs up to 50, the lcm is 3099044504245996706400. Do you really want a loop that tests every number up to that point to identify the lcm of the set?
Other schemes would seem far better. For example, factor each member of the sequence, then simply count the maximum number of occurrences of each prime factor. Or, build a simple prime sieve, that simultaneously factors the set of numbers, while allowing you to count factor multiplicities.
These schemes can be written to be highly efficient. Or you can use brute force. The latter seems silly here.
Michal is correct about the problem. A sieve will be a little bit faster, since no gcd calculations are needed:
EDIT: This code is actually horribly wrong. I've left it here to remind myself to check my work twice if I have such a hangover.
(ns euler (:use clojure.contrib.math))
(defn sieve
([m] (sieve m (vec (repeat (+ 1 m) true)) 2))
([m sieve-vector factor]
(if (< factor m)
(if (sieve-vector factor)
(recur m
(reduce #(assoc %1 %2 false)
sieve-vector
(range (* 2 factor) (+ 1 m) factor))
(inc factor))
(recur m sieve-vector (inc factor)))
sieve-vector)))
(defn primes [m] (map key (filter val (seq (zipmap (range 2 m) (subvec (sieve m) 2))))))
(defn prime-Powers-LCM [m] (zipmap (primes m) (map #(quot m %) (primes m))))
(defn LCM [m] (reduce #(* %1 (expt (key %2) (val %2))) 1 (seq (prime-Powers-LCM m))))