Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is range() not inclusive when given with float range and interval?

Tags:

php

php-7

php-7.1

The documentation states that the $end of the range is inclusive. And this is the case most of the time, but when both $end and $step are floats, the last value is missing. Why is that?

print_r(range(1, 13, 1));
print_r(range(1, 13, 0.1));
print_r(range(0.1, 1.3, 0.1));

Output:

Array
(
    [0] => 1
    [1] => 2
    // ...
    [11] => 12
    [12] => 13
)
Array
(
    [0] => 0.1
    [1] => 0.2
    // ...
    [119] => 12.9
    [120] => 13
)
Array
(
    [0] => 0.1
    [1] => 0.2
    // ...
    [10] => 1.1
    [11] => 1.2
    // 12 => 1.3 is missing
)
like image 396
nCrazed Avatar asked Jan 19 '17 21:01

nCrazed


People also ask

Can range be used with floats?

The Python range() works only with integers. It doesn't support the float type, i.e., we cannot use floating-point/decimal value in any of its arguments. For example, If you use range() with float step argument, you will get a TypeError 'float' object cannot be interpreted as an integer .

What is the range of values for float?

Since the high-order bit of the mantissa is always 1, it is not stored in the number. This representation gives a range of approximately 3.4E-38 to 3.4E+38 for type float.

What range of values can you store in a float variable Java?

The float covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Its default value is 0.0f. Its default size is 4 byte. It can be used to save memory in large arrays of floating point numbers.

How do you define a float range in Python?

NumPy linspace function to generate float range of float numbers. It has the following syntax: # Syntax linspace(start, stop, num, endpoint) start => starting point of the range stop => ending point num => Number of values to generate, non-negative, default value is 50. endpoint => Default value is True.


1 Answers

The range is inclusive; however, your assumptions about the numbers adding up are incorrect.

0.1 cannot be represented in binary with exact precision. When you use it in a calculation in php, you'll actually get a number that's a little higher or lower. Take a look at the following codepad:

http://codepad.org/MkoWgAA1

<?php

$sum = 1.0 + 0.1 + 0.1;

if ($sum > 1.2) {
  print("1.2 > 1.2");
} else if ($sum < 1.2) {
  print("1.2 < 1.2");
} else {
  print("1.2 == 1.2");
}

Output:

1.2 > 1.2
like image 180
Sam Dufel Avatar answered Sep 27 '22 17:09

Sam Dufel