# Getting wrong values when using \div (÷) operator

Hello,
I’ve stumbled upon a bug when using the \div (÷) operator:

`````` 20÷1
> 20
``````

produces the expected result 20, but

``````20÷0.1
> 199.0
``````

gives the result 199.0. This continues up until dividing by 1e-6, from which point on I get the expected results again.

I’m using Julia version 1.8.4

Are you perhaps looking for floating-point division, which you get by the `/` operator?

It’s not a bug, but could be documented in the div docs. You’ll find the explanation here:
https://docs.julialang.org/en/v1/base/math/#Base.fld

What is happening here is that the true value of the floating-point number written as `0.1` is slightly larger than the numerical value 1/10 while `6.0` represents the number 6 precisely. Therefore the true value of `6.0 / 0.1` is slightly less than 60. When doing division, this is rounded to precisely `60.0` , but `fld(6.0, 0.1)` always takes the floor of the true value, so the result is `59.0` .

And, you should be using proper float division with `/`, not `div`.

1 Like

What I am trying to do is create a vector of length

``````(upper_limit - lower_limit) / step_size + 1
``````

Without having to use the `round()` function, though I might have to use it here looking at @DNF 's answer.

``````julia> collect(range(0,20,step=0.1))
201-element Vector{Float64}:
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
⋮
19.3
19.4
19.5
19.6
19.7
19.8
19.9
20.0
``````

The vector I’m creating / initializing here is supposed to be filled with zeros, so this unfortunately doesn’t help.

You may be interested in one of the following.

``````julia> lower_limit, upper_limit, step_size = 0, 20, 0.1
(0, 20, 0.1)

julia> range(lower_limit, upper_limit; step = step_size) |> collect
201-element Vector{Float64}:
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
⋮
19.2
19.3
19.4
19.5
19.6
19.7
19.8
19.9
20.0

julia> LinRange(lower_limit, upper_limit, 201)
201-element LinRange{Float64, Int64}:
0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,…,19.4,19.5,19.6,19.7,19.8,19.9,20.0
``````

Can you explain why you want to avoid` round`? `div` with floats does rounding internally, so is it just a question of avoiding verbosity?

zero(range(0,20,step=0.1))

1 Like

This might work, but it doesn’t really signal the intent of the code, just “Do whatever `range` does”. Will it work equally well for other input values? We don’t know, because the OP’s intent is unclear.

Using, for example,

``````round(Int, (upper_limit - lower_limit) / step_size) + 1
``````

would make it crystal clear.

(Edit: forgot the `Int` argument to `round`)

Yes, it was just a matter of me wanting cleaner looking code.
The reason I started this thread wasn’t even the issue of creating the array, I just thought the `div` behaviour was unintended as I didn’t see the doc comment about it.
I’m still grateful for all the suggestions.