About float/double type number in range.

Richard Damon Richard at Damon-Family.org
Wed Aug 26 07:48:37 EDT 2020


On 8/25/20 10:39 PM, ADITYA wrote:
>    Dear Sir/Ma’am
>
>    I am requesting you to satisfy me about float number in Range function,
>    because in the argument of range we can take integer but not double or
>    float whenever double as well as float are integer in nature but when we
>    use double/float in, it gives error that- “'float' object cannot be
>    interpreted as an integer.” If we want to increment the number by half or
>    quarter what can I do.
>
>    For ex- Range(1,3,0.5) I want it gives Output as [1 1.5 2 2.5 3)
>
>    I am requesting to change the nature of increment number nature in above
>    example so that we can increase the number with half or quarter any point
>    value.
>
>    Your Sincerely
>
>    Aditya Gautam
>    Saharsa (Bihar)
>    India
>    Postal Code- 852201

As was indicated, Range(1, 3, 0.5) if legal would generate ([1, 1.5, 2,
2.5] because range excludes the top value. This case happens to work in
the sense that if Python allowed it, this is the result that would come
out. On the other hand, the very similar Range(1, 3, 0.4) would be need
very detailed knowledge to predict, it could return [1, 1.4, 1.8, 2.2,
2.6] as expected or [1, 1.4, 1.8, 2.2, 2.6, 3.0]. The issue is that
there is no such exact number in binary floating point as 0.4, (it is
like trying to write out exactly 1/3), so the actual value used for 0.4
will be either slightly higher (where you get the expected value) or
slightly lower (where you would get the top 'excluded' value listed).
This sort of unpredictability is part of the difficulty dealing with
floating point.

As was pointed out, you can scale the range, or build your own generator
to get what you want.

-- 
Richard Damon



More information about the Python-list mailing list