This question already has answers here:
Python: range function for decimal numbers [duplicate]
(4 answers)
How do I use a decimal step value for range()?
(34 answers)
Closed 8 years ago.
Using Python 3.4 and I have a list which has numbers in it which have 8 decimal places or more (eg. -72.2373909452 and 175.33903215), and I need a way to separate them according to their number.
Original code looks like this:
for number in list:
range_list=[]
if number in range(x, y):
range_list.append(number)
but for obvious reasons it doesn't work and doesn't add any numbers to the new list.
I also thought about multiplying the number first and then just having the range numbers between factors of ten, but as the number of decimal places is different between each number that isn't practical.
If I understand well, you want to check if number is between x and y.
Just use comparisons then. The following has the same behavior the "number in range(x, y)" solution has with integers:
if x <= number < y:
range_list.append(number)
Even if number is an integer, this sort of comparison is clearer and most likely faster than the solution involving range.
On a side note, you should define range_list outside of the for loop, otherwise you'll end up emptying the list with each loop:
range_list=[]
for number in my_list:
if x <= number < y:
range_list.append(number)
Related
This question already has answers here:
How to implement conditional string formatting? [duplicate]
(3 answers)
Closed 1 year ago.
I currently am trying to work with a number that has variable decimal place lengths. It can either be an integer, or have up to 10 decimals i.e. 33.3333333. I wanted to restrict the number to only have 2 decimals when it exceeds the length, or maintain the original if it's less.
I've tried using "{:0:.2f}".format, but the problem is that for integers, it also adds .00 to the end of the string.
When I tried using round(3) it'll return 3.0.
Is there a method, preferably a single line, that can convert 3.333333 to 3.33 but still allow for 3 to stay as an int?
Try choosing the format as a function of the values wholeness:
"{d}" if int(a) == a else "{:0:.2f}"
Can you finish from there?
You can use a conditional expression to choose the format based on the type of the variable:
for x in (33.3333333, 3):
print(("{:0}" if isinstance(x, int) else "{:.2f}").format(x))
You could also implement it using a dictionary to map types to format strings:
formats = {int: "{:0}", float: "{:.2f}"}
for x in (33.3333333, 3):
print(formats.get(type(x)).format(x))
This question already has answers here:
Python round up integer to next hundred
(10 answers)
Closed 2 years ago.
This is my code so far:
number = 201234
print(f'number is {number:,.0f}')
This prints: number is 201,234
However I want it to print: number is 200,000
I've tried using print(f'number is {number:,.1g}') but this prints in scientific notation like so: number is 2e+05
Is there a simple way to format this to get the desired outcome?
Use the round() function with a negative argument.
number = 201234
print(f'number is {round(number, -5):,.0f}')
Prints
number is 200,000
This question already has answers here:
range() for floats
(23 answers)
Closed 2 years ago.
I'm trying to print the numbers between 0.00001 and 0.1, where i tried:
for i in range(0.00001,0.1):
print(i)
But python throws an error saying it cannot be interpreted as integers. Is it possible to do something like this in python?
range only supports integers. Lets define our own
def frange(start, stop, step):
while start < stop:
yield start
start += step
for i in frange(0.5, 1.0, 0.1):
print(i)
From the range() method documentation we can read the following:
The arguments to the range constructor must be integers (either built-in int or any object that implements the __index__ special method).
You also didn't specify the step you want to have. Because there are infinitely many real numbers between any 2 unique real numbers, you can't really get all of them.
What you can do is multiply both sides of the range by the same number until they are both integers and then when doing stuff with them divide them by that number again. I'm going to assume you wanted to have a step of 0.00001
mult = 100000
for i in range(1, 10000):
print(i/mult)
If you want any different step, simply supply a third argument to the range() method.
This question already has answers here:
How do you check whether a number is divisible by another number?
(9 answers)
Closed 6 years ago.
Wondering what is the most efficient way to check if an integer can or cannot be divided by another number (could be float) in Python 2.7. Or more general, what is the most efficient way to check if an integer can be divided by n (n could be a float number) in Python 2.7.
My pain point is, if I try to get x/n, it is always an integer.
Try
if x % n == 0 :
hope this helps !
Here:
x = 25
y = 2.5 # Or something
if not x % y: # Works with float too
print 'can divide'
else:
print 'cannot divide'
This question already has answers here:
approximate comparison in python
(3 answers)
Closed 8 years ago.
I just recently ran into a problem where I needed to append numbers to a list only if they weren't in the list already, and then I had to run those numbers through a comparison later on. The problem arises in floating point arithmetic errors. To illustrate what is basically happening in my code:
_list = [5.333333333333333, 6.666666666666667, ...]
number = some_calculation()
if number not in _list:
_list.append(number) #note that I can't use a set to remove
#duplicates because order needs to be maintained
new_list = []
for num in _list:
if some_comparison(num): #note that I can't combine 'some_comparison' with the
new_list.append(num) #above check to see if the item is already in the list
The problem is that some_calculation() would sometimes generate an inexact number, such as 5.333333333333332, which is, as far as my calculations need to go, the same as the first element in _list in this example. The solution I had in mind was to simply round all the numbers generated to 9 or so decimal places. This worked for a short amount of time, until I realized that some_comparison compares num against, again, an inexact calculation. Even if I didn't round the numbers in _list, some_comparison would still return an inexact value and thus would evaluate to False.
I am absolutely puzzled. I've never had to worry about floating point errors so this problem is quite infuriating. Does anyone have any ideas for solutions?
NOTE: I would post the actual code, but it's very convoluted and requires 7 or 8 different functions and classes I made specifically for this purpose, and reposting them here would be a hassle.
Make the comparison something like
if(abs(a-b) <= 1e-6 * (a + b)):
This is standard practice when using floating point. The real value you use (instead of 1e-6) depends on the magnitude of the numbers you use and your definition of "the same".
EDIT I added *(a+b) to give some robustness for values of different magnitudes, and changed the comparison to <= rather than < to cover the case where a==b==0.0.
You can subclass list and add in a tolerance to __contains__:
class ListOFloats(list):
def __contains__(self, f):
# If you want a different tolerance, set it like so:
# l=ListOFloats([seq])
# l.tol=tolerance_you_want
tol=getattr(self, 'tol', 1e-12)
return any(abs(e-f) <= 0.5 * tol * (e + f) for e in self)
_list = ListOFloats([5.333333333333333, 6.666666666666667])
print(5.333333333333333 in _list)
# True
print(6.66666666666666 in _list)
# True
print(6.66666666666 in _list)
# False
Use round on both the values in the list and the comparison values. They won't be exact but they'll be consistent, so a search will return the expected results.