Frage

I am trying to solving pythonchallenge problem using Clojure:

(java.lang.Math/pow 2 38)

I got

2.74877906944E11

However, I need to turn off this scientific notation. I searched clojure docs, still don't know what to do. Is there a general way to toggle on/off scientific notation in Clojure?

Thanks.

War es hilfreich?

Lösung

You can use format to control how results are printed.

user> (format "%.0f" (Math/pow 2 38))
"274877906944"

Also, if there is no danger of losing wanted data, you can cast to an exact type:

user> 274877906944.0
2.74877906944E11
user> (long 274877906944.0)
274877906944

There are BigInts for larger inputs

user> (bigint 27487790694400000000.0)
27487790694400000000N

Andere Tipps

Warning

You can often lose precision by using java.lang.Math/pow to compute an integer power of an integer.

For example

(bigint (java.lang.Math/pow 3 38))
; 1350851717672992000N

whereas

(int-pow 3 38)
; 1350851717672992089

It works with powers of 2 because - if you look at them in binary - there is a single 1 bit with all the rest 0s. So the hex exponent just keeps going up while the solitary 1 bit floats around in the significand. No precision is lost.

By the way, int-pow above is just repeated multiplication:

(defn int-pow [b ^long ex]
  (loop [acc 1, ex ex]
    (case ex
      0 acc
      (recur (* acc b) (dec ex)))))

This is more a comment than a solution, but doesn't fit as such.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top