# Float to int transformations drive me crazy

#1

Tryed avoiding the int->str dirty tricks, but float to int transformations drive me crazy.

``````from math import floor
def digit_sum(n):
a=n
total=0
while a>9:
a=float(a)/10
total+=(a-floor(a))*10
a=floor(a)
total+=a
return total``````

Depending on the place I try to convert total variable from float to int the difference may get up to 2 if test against n=434

How to wite digit_sum?
#2

The accuracy question is still a question, but i found a much easier solution:

``````from math import floor
def digit_sum(n):
a=n
total=0
while a>9:
total+=(a-a//10*10)
a=a//10
total+=a
return total``````

Anyway, how do you manage such cases when converting float to int?

#3

``````>>> digit_sum(434)
10.999999999999984
>>>``````

This is telling us something.

#4

Consider:

Since n is a value we can destroy it in the function, which means no need for `a`.

``````    total = 0
while n > 0:
total += n % 10
n //= 10
return total``````

Let's compare notes...

``n % 10``

is the equivalent of

``(a - a // 10 * 10)``

though in a roundabout way.

Consider:

``````>>> 434 % 10
4
>>> 43 % 10
3
>>> 4 % 10
4``````

``````434 - 434 // 10 * 10  => 434 - 43 * 10  => 4
43 - 43 // 10 * 10    => 43 - 4 * 10    => 3
4 - 4 // 10 * 10      => 4 - 0 * 10     => 4``````

The earlier example had a float result when we wanted an integer. That suggests we need to cast the return value as int.

``return int(total)``

But that would be 10, not 11. This suggests the need for some rounding in the intermediate float results.

``total += round((a - floor(a)) * 10, 0)``

Now we get the expected result:

``````>>> digit_sum(434)
11
>>>``````

#5

just takes practice

#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.