Why is 10/3 equal to 3.3333333333333335 instead of ... 332 or ..334?

Can someone specifically explain why the last digit is 5 instead of 2 or 4? Knowledge of the float must be inaccurate in the binary world, I can’t understand exactly how the result of the above was made.

+4
source share
2 answers

This is because the closest (64 bit) floatmay be the "true value" 10/3.

I use cython here (to wrap math.h nexttoward) because I don't know any built-in function for this:

%load_ext cython

%%cython
cdef extern from "<math.h>" nogil:
    # A function that get the next representable float for the 
    # first argument in direction to the second argument.
    double nexttoward(double, long double)

def next_float_toward(double i, long double j):
    return nexttoward(i, j)

(or, as pointed out by @DSM, you can also use numpy.nextafter)

10/3 , :

>>> '{:.50}'.format(10/3)
3.3333333333333334813630699500208720564842224121094

>>> '{:.50}'.format(next_float_toward(10/3., 0))
3.3333333333333330372738600999582558870315551757812

>>> '{:.50}'.format(next_float_toward(10/3., 10))
3.3333333333333339254522798000834882259368896484375

, "".

+6

... 335 ... 330 ( , 2**-51 ).... 333 ... 335, ... 330, .

; MSeifert , <math.h> C Cython. ( Googling " " ) .

+5

Source: https://habr.com/ru/post/1664024/


All Articles