Reputation: 60
This is just for learning purpose. I want to do the following.
x = 5.0
y = 888.0
z= y / x
print z # 177.6
...?
Now I want to change the last part of the float to int and add the last number of the float (.6) as 6 to the first number (to get 777 from 177.6). After that I want to add the difference of 777 and y to a new variable to get 888 back.
Would be great if someone can explain how to do that! :) edit: possible solution in the last code of this post.
The purpose of this is to understand how to perform such tasks in python and to get a better understanding of something I would call "mathematic symmetry".
You can find this symmetry while performing calculations like:
666 / 5.0 #133.2
777 / 5.0 #155.4
888 / 5.0 #177.6
999 / 5.0 #199.8
666.6 / 5.0 #133.32
I'm not an academic, so maybe this sounds mad. It is just a part of a theory in my spaghetti monster mind and with a script I could further investigate what this is about. ;)
With the help of the comments i was able to create this code. I'm quite sure it looks ugly from a professional programmers view, but hey, it's one of my first steps and im very happy with that! Thank you again! :)
x = 5.0
y = 888.0
z= y / x
print z # 177.6
print
a = int(str(z)[0])
print "First Number = " + str(a)
print
b = int(str(z)[1])
c = int(str(z)[2])
print "In between = " + str(b) + str(c)
d = int(str(z)[-1]) # treat z as string, take first string after . from z and format it back to int
print "Last Number = " + str(d)
print
res = str(a+d) +str(b) +str(c)
to_int = int(res)
dif = y - to_int
add = to_int + dif
print add
Edit: Is there some magic happening in this code? The actual code seems to be inteded to calculate numbers like 777.7 But when i run it with y = 7277.7727 it gives the correct output even if i only have 2 digits in between? I was expecting wrong calculations. o0
Edit: Resolved. A logical failure in the calculations created the unexpected result. Practically i was printing y at the end. xD
Upvotes: 0
Views: 458
Reputation: 12610
I think the safest way is using string manipulation:
int(str(177.123)[-1])
3
int(str(177.123).split('.')[-1])
123
But I am afraid you'll be eventually bitten by floating point precision issues. A package for symbolic math like sympy might be more suitable for your purpose than standard floating point arithmetic.
Upvotes: 1