What about using:
min(a, b) < x < max(a, b)
Answer from Marcelo Villa on Stack OverflowWhat about using:
min(a, b) < x < max(a, b)
came up with these four:
min(a, b) < x < max(a, b)
a < x < b if a < b else b < x < a
(a - x) * (b - x) < 0
not (b < x > a and a < x > b)
but still think your version is the best.
python - Check if a number is between two values, which can be given in any order - Stack Overflow
list - Finding if float is between two floats in python - Stack Overflow
float numbers with range () function
if statement - Check if user input is between two floats - Python - Stack Overflow
How do I check if a number is between two values in Python?
Why does my float range check fail?
How do I check a range on a NumPy array or pandas column?
Why not sort the bounds first?
r = range(*sorted((4, -1)))
q = range(*sorted((-1, 4)))
range doesn't do what you think it does.
It creates a list; it's not a numeric range (edit: actually it does in Python 3).
Just imagine a case, when the lowerEnd is -20000 and the upperEnd is +20000. Using the range( -20000, 20000 ) and comparing num in such a range() is a waste of both memory and CPU-power.
It is quite enough to compare a num against lowerEnd & upperEnd limit
You want to check:
num = 3
print(-1 < num < 4)
You could iterate over a dictionary mapping actions to the lower/upper bound, doing comparisons against that dictionary:
# I used strings here which I print in the function, but you could very well
# assign methods as values.
checkme = {1.0:"hi!",2.3:"bye",3.4:"hello!"}
final = "goodbye"
def findBucket(aFloat):
for key in checkme.keys():
if aFloat < key:
print checkme[key]
return
# getting to this point means aFloat was greater than the last key
print final
return
Alternative solution, with two lists:
checkme = [1.0, 2.3, 3.4]
checkme2 = ['hi', 'bye', 'hello', 'finalanswer']
def findBucket(aFloat):
i = 0
while i < len(checkme):
if aFloat < checkme[i]:
print checkme2[i]
return
i += 1
print checkme2[-1] #negative indexing starts from the end of the list in python
return
import pandas as pd
def findBucket(aFloat):
df = pd.DataFrame({'A': [21.2,18.8,14.2,9,5.7,2.9,0.6,-1.6],
'B': [25.4,21.9,14.7,10.4,7,5,3.5,2.3]})
return(df.B.iloc[df.A.apply(lambda x: x if aFloat - x > 0 else 0).idxmax()])
Explanation:
- Populate a data frame with values as defined by OP.
- Calculate (aFloat - <entries in column A>); if any happens to be negative, substitute with zero. This helps in finding the largest value in column A that is less than aFloat.
- Find the index idx where the largest value thus calculated resides in column A
- Find the value in the column B, index idx and return it.
Hi, I have a section of code which takes a score from the user, typecasts it into a float value and saves it under the variable name "score". Then I have a line of code which reads:
while score not in range(0, 101):
However, when I input a float, I get an invalid input error message from python. I think it's because I can't use the range() function with floats. Is there a way around this? If anyone knows how to solve this, then your help would be greatly appreciated. Thank you in advance.
Is that you are looking for?
def check(value):
if 0.50 <= value <= 150 and round(value,2)==value:
return True
return False
Given your comment:
i input 15.22366 it is going to return true; that is why i specified the range; it should accept 15.22
Simply said, floating point values are imprecise. Many values don't have a precise representation. Say for example 1.40. It might be displayed "as it":
>>> f = 1.40
>>> print f
1.4
But this is an illusion. Python has rounded that value in order to nicely display it. The real value as referenced by the variable f is quite different:
>>> from decimal import Decimal
>>> Decimal(f)
Decimal('1.399999999999999911182158029987476766109466552734375')
According to your rule of having only 2 decimals, should f reference a valid value or not?
The easiest way to fix that issue is probably to use round(...,2) as I suggested in the code above. But this in only an heuristic -- only able to reject "largely wrong" values. See my point here:
>>> for v in [ 1.40,
... 1.405,
... 1.399999999999999911182158029987476766109466552734375,
... 1.39999999999999991118,
... 1.3999999999999991118]:
... print check(v), v
...
True 1.4
False 1.405
True 1.4
True 1.4
False 1.4
Notice how the last few results might seems surprising at first. I hope my above explanations put some light on this.
As a final advice, for your needs as I guess them from your question, you should definitively consider using "decimal arithmetic". Python provides the decimal module for that purpose.
float is the wrong data type to use for your case, Use Decimal instead.
Check python docs for issues and limitations. To quote from there (I've generalised the text in Italics)
Floating-point numbers are represented in computer hardware as base 2 (binary) fractions.
no matter how many base 2 digits you’re willing to use, some decimal value (like 0.1) cannot be represented exactly as a base 2 fraction.
Stop at any finite number of bits, and you get an approximation
On a typical machine running Python, there are 53 bits of precision available for a Python float, so the value stored internally when you enter a decimal number is the binary fraction which is close to, but not exactly equal to it.
The documentation for the built-in round() function says that it rounds to the nearest value, rounding ties away from zero.
And finally, it recommends
If you’re in a situation where you care which way your decimal halfway-cases are rounded, you should consider using the decimal module.
And this will hold for your case as well, as you are looking for a precision of 2 digits after decimal points, which float just can't guarantee.
EDIT Note: The answer below corresponds to original question related to random float generation
Seeing that you need 2 digits of sure shot precision, I would suggest generating integer random numbers in range [50, 15000] and dividing them by 100 to convert them to float yourself.
import random
random.randint(50, 15000)/100.0
What is the right way to see if a value is between two number. For example: number = 5 + 9 if number == [5 <=> 24]: print(“yes”)
Hi!
Im wondering how to check if a value is a float or int using an if else statement.
E.g
test = int(input("Add a random number!"))
value = test / 4
if ..............?
print("Hello")
else:
print("Hello2")
I have no idea if this is even close to being the right way to do it since i just started to learn Python and have no prior experience in programming.
Can someone please show me the way to do it since I can't find the answer on the internet!!
If you just want to get a True or False result, consider the following.
>>> a = 0.4
>>> b = 0.6
>>>
>>> ranges = [[0,0.33], [0.33,0.66], [0.66,1.0]]
>>>
>>> any(low <= a <= high and low <= b <= high for low, high in ranges)
True
If you have an arbitrary amount of numbers to check (not just a and b) you can generalize this to:
>>> numbers = [0.4, 0.6, 0.34]
>>> any(all(low <= x <= high for x in numbers) for low, high in ranges)
True
Like this:
RANGES = [[0,0.33], [0.33,0.66], [0.66,1.0]]
def check(no_a, no_b):
for rng in RANGES:
if rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1]:
return True
else:
return False
print(check(.1, .2))
print(check(.1, .4))
Output is:
True
False
Or like this:
no_a, no_b = .1, .2
print(any(rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1] for rng in RANGES))
no_a, no_b = .1, .4
print(any(rng[0] < no_a < rng[1] and rng[0] < no_b < rng[1] for rng in RANGES))
Output is:
True
False