Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have been programming in google Golang and have been enjoying it due to its brevity but I find it surprising that almost all its Math standard library methods are for the floating point type. Is there any particular reason why these methods do not exist for ints?

share|improve this question
add comment

1 Answer

The short answer is that Go is a successor to C, and C's standard math library is also defined almost exclusively in terms of single- and double-precision floating point values.

The longer answer is that in a statically-typed language without polymorphism or function overloading, like Go (or C), you need to settle on a type for a function to take and return in advance, and once you're going to deal with specific types in your math library, there are a lot more interesting operations on floating point numbers than integers. To pick a few examples

  • the square or nth root of an integer or floating point number is usually not representable as an integer

  • very few interesting values of transcendental functions are representable as integers

  • division of floating point values requires less rounding than division of integers

Note that this is not as onerous as it might seem if your input values are integers -- an integral value can be converted to a floating point value with a simple typecast, and mostly accurately.

So that's the story for languages like Go or C. Other languages have other options:

  • A dynamically typed language can provide math library functions which take or return multiple types depending on what they are called with or whether the return value is representable as an integer.

  • A language with function overloading can provide multiple versions of the same function, depending on the types you pass (strictly, these are multiple functions with the same name, as distinct from the dynamically typed case above)

  • A language with type polymorphism (such as object oriented languages with inheritance) can define a superclass "Number" with subclasses for both integers and floating point values, and then define math functions in terms of this Number class. This approach has much of the flexibility of the dynamic language approach, while still keeping much of the strictness of the static or function-overloading approach.

Go has none of these features, however.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.