On 26/08/2020 19:58, Joel Goldstick wrote:
On Wed, Aug 26, 2020 at 3:43 AM ADITYA <gautam.goari...@gmail.com> 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)


Take a look at this:
l = [i/2 for i in range(2,7)]
l
[1.0, 1.5, 2.0, 2.5, 3.0]


This is a neat solution! To make it more user-friendly, the above needs to be wrapped in a convenience function that the user can call using arguments like "(1,3,0.5)" and not have to think about the 'multiplies' and 'divides'.

The problem with constructing such a list is that it is 'expensive', ie if the range is large, more storage-space will be required. In the same way that range() moved to a storage-averse model in Python3, herewith a pair of generator solutions - it might be quite fun to compare the performances (PSL's time library).

My first thought was that the count() from the itertools library enables one to step using a floating-point number. So, herewith two generator-based solutions:-


<<< Code NB Python v3.8 >>>
def fp_range( start:float, stop:float, step:float=1.0 )->float:
    """Generate a range of floating-point numbers."""
    if stop <= start:
        raise OverflowError( "RangeError: start must be less than stop" )
    x = start
    while x < stop:
        yield x
        x += step

try:
    for fp_number in fp_range( 1, 3, 0.5 ):
        print( fp_number )
except OverflowError as e:
    print( e )

print( "*"*12 )

try:
    for fp_number in fp_range( 1, 3, 0.25 ):
        print( fp_number )
except OverflowError as e:
    print( e )

print( "+"*12 )
import itertools

def fp_iter( start:float, stop:float, step:float=1.0 )->float:
"""Generate a range of floating-point numbers using itertools.count()."""
    if stop <= start:
        raise OverflowError( "RangeError: start must be less than stop" )
    for x in itertools.count( start, step ):
        if x >= stop:
            break
        yield x


for fp_number in fp_iter( 1, 3, 0.5 ):
    print( fp_number )

print( "*"*12 )

for fp_number in fp_iter( 1, 3, 0.25 ):
    print( fp_number )

print( "*"*12 )

try:
    for fp_number in fp_iter( 3, 1, 0.5 ):
        print( fp_number )
except OverflowError as e:
    print( e )


<<< Console.out >>>

1
1.5
2.0
2.5
************
1
1.25
1.5
1.75
2.0
2.25
2.5
2.75
++++++++++++
1
1.5
2.0
2.5
************
1
1.25
1.5
1.75
2.0
2.25
2.5
2.75
************
RangeError: start must be less than stop

--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to