Search code examples
gomath

How to round up on a log10


This Go code gives me an error stating that operation ^ is not defined on a float64

10 ^math.Ceil(math.log10(5693440))

The number I'm passing to math.log10 is an int. What am I doing wrong in this function? (Please note, I don't understand Math)

Note, if it helps provide clarity, I'm trying to create a function in Go that does something similar to d3.js scale.ticks() function, which creates values for a Y axis of a graph. The idea behind the above Go code is that I could divide the result of 10 ^math.Ceil(math.log10(5693440)) by 5 and then multiply to create ticks for a Y axis of a graph


Solution

  • The ^ operator is documented in the Go spec under Arithmetic_operators as

    ^    bitwise XOR            integers
    

    This is neither exponentiation nor does it operate on floats.

    Both math.Log10 and math.Ceil take a float64 and return a float64, so you are working with floats even if you think your argument to math.Log10 is an integer (it is a constant so converted for you).

    For exponentiation, use math.Pow:

    func Pow(x, y float64) float64

    Pow returns x**y, the base-x exponential of y.

    i.e.

    math.Pow(10, math.Ceil(math.Log10(5693440)))
    

    Note that math.Pow returns a float64 as with the other math functions you used.