range() for floats
I don't know a built-in function, but writing one like [this](https://stackoverflow.com/a/477610/623735) shouldn't be too complicated.
def frange(x, y, jump):
while x < y:
yield x
x += jump
---
As the comments mention, this could produce unpredictable results like:
>>> list(frange(0, 100, 0.1))[-1]
99.9999999999986
To get the expected result, you can use one of the other answers in this question, or as @Tadhg mentioned, you can use decimal.Decimal
as the jump
argument. Make sure to initialize it with a string rather than a float.
>>> import decimal
>>> list(frange(0, 100, decimal.Decimal('0.1')))[-1]
Decimal('99.9')
Or even:
import decimal
def drange(x, y, jump):
while x < y:
yield float(x)
x += decimal.Decimal(jump)
And then:
>>> list(drange(0, 100, '0.1'))[-1]
99.9
[editor's not: if you only use positive jump
and integer start and stop (x
and y
) , this works fine. For a more general solution see here.]
Function for Range for floats in python
The main reason you're getting answers wrong is the top level if
statements are wrong. You don't want to look at the boundaries when deciding which way to move. It's legal to ask for a range that has nothing in it (with e.g. stop
less than start
with a positive step
).
Here's how I'd minimally adjust your code to work properly:
def float_range(start,stop,step):
x = start
my_list = []
if step > 0:
while x < stop:
my_list.append(x)
x += step
else: # should really be if step < 0 with an extra check for step == 0
while x > stop:
my_list.append(x)
x += step
return my_list
How do I use a decimal step value for range()?
Rather than using a decimal step directly, it's much safer to express this in terms of how many points you want. Otherwise, floating-point rounding error is likely to give you a wrong result.
Use the linspace
function from the NumPy library (which isn't part of the standard library but is relatively easy to obtain). linspace
takes a number of points to return, and also lets you specify whether or not to include the right endpoint:
>>> np.linspace(0,1,11)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.linspace(0,1,10,endpoint=False)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
If you really want to use a floating-point step value, use numpy.arange
:
>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
Floating-point rounding error will cause problems, though. Here's a simple case where rounding error causes arange
to produce a length-4 array when it should only produce 3 numbers:
>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])
Find range between floats in python
if 0.5 <= x < 3.5:
pass
You might want to change the inequality signs depending on whether you want the ends to be inclusive or exclusive.
A "range" in Python is not an abstract mathematical notion of "all the numbers between these two numbers", but either an actual list of numbers (range()
in Python 2) or a generator which is capable of producing a sequence of numbers (xrange()
in Python 2 or range()
in Python 3). Since there are infinitely many real numbers between two given numbers, it's impossible to generate such a list/sequence on a computer. Even if you restrict yourselves to floating-point numbers, there might be millions or billions of numbers in your range.
For the same reason, even though your code would have worked for integers (but only in Python 2), it would have been terribly inefficient if your endpoints were far apart: it would first generate a list of all integers in the range (consuming both time and memory), and then traverse the list to see if x
is contained in it.
If you ever try to do a similar thing in other languages: most languages don't allow double comparisons like this, and would instead require you to do something like if 0.5 < x and x < 3.5
.
How to interpret int to float for range function?
I believe that this should do what you want:
import math
x = float(input('x: '))
n = int(input('n: '))
s = 0
if 0.1 <= x <= 1:
for i in range(1, n + 1):
s += ((-1)**i * x**(4 * i + 3)) / (math.factorial(2*i + 1) * (4*i + 3))
print(s)
Key note is that the range function must take in integers, so you must convert n into an int.
I think that you've used a while loop where an if statement should have been used. Let us know if we've misinterpreted your objective, it may help to explicitly say what the summation is supposed to be.
PHP how to use range() for float numbers
The third parameter is the step
.
Reading the documentation is a very good place to start.
If you read you will see that you can set the step to something that can increment between your limits.
The error message is simply telling you that it cannot increment 0.54 by 1 without going over 0.58 - think about, it 1 + 0.54 is more than 0.58!
Using this line instead will give you the desired output.
range(0.54, 0.58, 0.01);
Range with step of type float
You could use numpy.arange
.
EDIT: The docs prefer numpy.linspace
. Thanks @Droogans for noticing =)
Range of int and float in Python
The first example with integers will loop until no memory is available (in which case the process will stop or the machine will swap to death):
x = 1000
while (1000 * x != x):
x = 1000 * x
because integers don't have a fixed size in python, they just use all the memory if available (in the process address range).
In the second example you're multiplying your floating point value, which has a limit, because it's using the processor floating point, 8 bytes (python float
generally use C double
type)
After reaching the max value, it overflows to inf
(infinite) and in that case
1000 * inf == inf
small interactive demo:
>>> f = 10.0**308
>>> f*2
inf
>>> f*2 == f*1000
True
>>>
how to efficiently create a range of float numbers
In [1]: import numpy as np
In [2]: np.repeat(1 / 10**np.arange(1, 5), 2)[1:] * np.array([1., 5.]*4)[:-1]
Out[2]: array([0.1 , 0.05 , 0.01 , 0.005 , 0.001 , 0.0005, 0.0001])
Generalizing for any "pattern":
def rates(smallest_magnitude, pattern):
n = len(pattern)
pows = np.repeat(1 / 10**np.arange(1, smallest_magnitude), n)[(n-1):]
mults = np.array(pattern * (smallest_magnitude - 1))[:-(n-1)]
return np.round(pows * mults, smallest_magnitude)
Demo:
In [4]: print(*rates(5, [1, 5])) # Your original 'pattern'
0.1 0.05 0.01 0.005 0.001 0.0005 0.0001
In [5]: print(*rates(5, [2, 4, 8]))
0.2 0.04 0.08 0.02 0.004 0.008 0.002 0.0004 0.0008 0.0002
In [6]: print(*rates(5, [3, 5, 7, 9]))
0.3 0.05 0.07 0.09 0.03 0.005 0.007 0.009 0.003 0.0005 0.0007 0.0009 0.0003
Related Topics
What Does a . in an Import Statement in Python Mean
Python Unexpected Eof While Parsing
Is There a Math Ncr Function in Python
Why Are Empty Strings Returned in Split() Results
How to Convert a Dataframe to a Dictionary
How to Expand a List to Function Arguments in Python
Why Does '.Sort()' Cause the List to Be 'None' in Python
Pretty Printing a Pandas Dataframe
How to Get Numbers After Decimal Point
How to Ignore Deprecation Warnings in Python
How to Use an Image for the Background in Tkinter
List to Dictionary Conversion with Multiple Values Per Key
Why Do I Need 'B' to Encode a String with Base64
Matplotlib Scatter Plot Legend