About float/double type number in range.
Peter J. Holzer
hjp-python at hjp.at
Wed Aug 26 07:02:55 EDT 2020
On 2020-08-26 22:40:36 +1200, dn via Python-list wrote:
> On 26/08/2020 19:58, Joel Goldstick wrote:
> > On Wed, Aug 26, 2020 at 3:43 AM ADITYA <gautam.goari123 at 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'.
>
[...]
> <<< 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
This is almost the same solution as I came up with, but note that this
is not quote the same as what Joel proposed. Repeated addition is not
the same as multiplication with floating point numbers.
A generator based on Joel's idea would look like this:
def fp_range(start, end, step):
v = start
n = int(math.ceil((end - start) / step))
for i in range(n):
yield start + i * step
(I omitted the OverflowError: range() doesn't raise one, either)
hp
--
_ | Peter J. Holzer | Story must make more sense than reality.
|_|_) | |
| | | hjp at hjp.at | -- Charles Stross, "Creative writing
__/ | http://www.hjp.at/ | challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20200826/01157bd3/attachment.sig>
More information about the Python-list
mailing list