Why doesn't trunc() turn a float into an integer?

Viewed 225

When doing trunc(3.5), it returns a float, 3.0, why?

I know that you can do trunc(Int64, 3.5), but isn't the purpose of trunc to convert a float into an integer? Why does it work this way?

1 Answers

Let us focus on the case when you pass a Float64 to trunc (the analysis can be similarly extended to other types). Take that the value you want to truncate is x.

First note that then trunc can always perform the truncation of x to the nearest integral value less or equal than it. So in short - this operation is always well defined, possible to perform, fast, and type stable.

If we wanted to return an integer we have a choice: do we want to be type stable. In Julia the answer in Base is yes. But this would mean that you would have to return BigInt value for the operation to be always well defined. But probably when you do trunc you do not expect to get BigInt as it will be expensive.

The alternative would be to return some other integer type, but then you would have to throw an error if the float is too large, again - this is something that most likely you do not want to get.

Here is an example showing the issue:

julia> x = 1e300
1.0e300

julia> trunc(x)
1.0e300

julia> trunc(Int, x)
ERROR: InexactError: trunc(Int64, 1.0e300)
Stacktrace:
 [1] trunc(::Type{Int64}, ::Float64) at ./float.jl:703
 [2] top-level scope at REPL[35]:1

julia> trunc(BigInt, x)
1000000000000000052504760255204420248704468581108159154915854115511802457988908195786371375080447864043704443832883878176942523235360430575644792184786706982848387200926575803737830233794788090059368953234970799945081119038967640880074652742780142494579258788820056842838115669472196386865459400540160

So in summary - because floats can span much wider range of value than normal integers the only safe option is to return float by default.

Related