Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Unexpected result
#1
I'm teaching myself python and used the following tutorial:

https://www.pythoncentral.io/pythons-ran...explained/

>>> def frange(start, stop, step):
...     i = start
...     while i < stop:
...         yield i
...         i += step
...
>>> for f in frange(0.5,3.0,0.1):
...     print(f)
Instead of increments in 0.1 steps I get:

Output:
0.5 0.6 0.7 0.7999999999999999 0.8999999999999999 0.9999999999999999 1.0999999999999999 1.2 1.3 1.4000000000000001 1.5000000000000002 1.6000000000000003 1.7000000000000004 1.8000000000000005 1.9000000000000006 2.0000000000000004 2.1000000000000005 2.2000000000000006 2.3000000000000007 2.400000000000001 2.500000000000001 2.600000000000001 2.700000000000001 2.800000000000001 2.9000000000000012 >>>
I can't work out why some of the increments have values that aren't exactly .1 from the previous.
Is there some secret floa behaviour?

Thanks.
Quote
#2
The python float 0.1 is not exactly equal to the same mathematical number because computers store numbers in binary form and the real number 0.1 cannot be represented exactly in base 2 on 64 bits. This is not a limitation of python, it is a limitation of the widely adopted IEEE754 floating point format used by computers. The true value of 0.1 in your program is
>>> (0.1).as_integer_ratio()
(3602879701896397, 36028797018963968)
You can read this documentation page for more.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Unexpected Output using classes and inheritance langley 2 145 Jul-04-2019, 09:33 AM
Last Post: langley
  remove tags from BeautifulSoup result moski 1 184 Jun-05-2019, 01:47 PM
Last Post: heiner55
  call dict object result key error lateublegende 2 231 May-15-2019, 01:08 PM
Last Post: lateublegende
  syntax error near unexpected token btom529 5 500 Apr-21-2019, 09:03 PM
Last Post: btom529
  Getting an unexpected generator object ? mcgrim 19 613 Mar-29-2019, 11:35 AM
Last Post: gontajones
  Force calculation result as decimal vercetty92 4 262 Mar-20-2019, 02:27 PM
Last Post: vercetty92
  Dictionary adds an unexpected list erina 1 234 Mar-14-2019, 01:13 PM
Last Post: ichabod801
  unexpected EOF while parsing whatloop 3 814 Mar-09-2019, 06:59 PM
Last Post: whatloop
  test pattern and add result in a table sam1975 1 217 Mar-05-2019, 02:41 PM
Last Post: sam1975
  My code is taking longer time to give result rajeshwin 4 296 Feb-20-2019, 08:18 PM
Last Post: ichabod801

Forum Jump:


Users browsing this thread: 1 Guest(s)