Python: range function for decimal numbers

断了今生、忘了曾经 提交于 2019-12-01 11:16:55

问题


Is there any range() function in python for float numbers for example

a=0.6

if a in range(0,1):
    a=3

How can i implement this?


回答1:


If I'm reading correctly, you want to test if a number is between two other numbers, so use:

a = 0.6
if 0 <= a < 1: # change to `<= 1` to be inclusive
   a = 3

You don't need to generate a range and do membership testing - unless you have a discrete set of values that your a should match - the builtin range in Python 3.x can do efficient lookups for ints as it can optimise membership testing. If you have a large amount of discrete values in a large range, then you'd be better of doing it mathematically anyway.




回答2:


Similar to the question linked by Begueradj but slightly different (note, floats are not the same as decimals):

import decimal

def drange(start, stop, step=decimal.Decimal('1')):
    while start < stop:
        yield start
        start += step

print(list(drange(
    decimal.Decimal('1.25'),
    decimal.Decimal('2.34'),
    decimal.Decimal('0.1'),
)))

Output:

[Decimal('1.25'), Decimal('1.35'), Decimal('1.45'), Decimal('1.55'),
 Decimal('1.65'), Decimal('1.75'), Decimal('1.85'), Decimal('1.95'), 
 Decimal('2.05'), Decimal('2.15'), Decimal('2.25')]



回答3:


assuming you have numpy installed do:

>>>import numpy

>>>print np.arange(0,1,0.1)

array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])

if you don't have Numpy installed, definitely go get it.




回答4:


If you're looking to check whether a is in between two numbers it's better to use:
0 <=a<=1
Otherwise , if you do need a list of say 0 to 1 in 0.1 jumps you can use this code to generate it:
lst = map(lambda x: x/10.0, range(11))



来源:https://stackoverflow.com/questions/27076503/python-range-function-for-decimal-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!