Reputation: 91
Is there any way on python to have two integers and merge them in a single float?
for example i have two variable var1=2 and var2=4 and i want to create a new variable var3=2.4
Upvotes: 6
Views: 6321
Reputation: 1509
Efficient method that works for any a and b:
from math import floor, log10
def combine(a, b):
if b == 0:
return a
return a + b * 10**-(floor(log10(b))+1)
Testing timing for this method and fredtantini's version:
from timeit import Timer
from random import randint
from math import floor, log10
def random_pair_generator(n):
i = 0
while i < n:
yield (randint(1, 1000000000), randint(1, 1000000000))
i += 1
def maths_combine(a, b):
if b == 0:
return float(a)
return a + b * 10**-(floor(log10(b))+1)
def string_combine(a, b):
return float(str(a) + '.' + str(b))
def time(n):
maths_time, string_time = 0, 0
for a, b in random_pair_generator(n):
maths_time += Timer(lambda: maths_combine(a, b)).timeit()
string_time += Timer(lambda: string_combine(a, b)).timeit()
print('Maths time:', maths_time)
print('String time:', string_time)
>>> time(20)
Maths time: 31.402130099450005
String time: 49.468994391525484
As expected, using maths is much faster.
Upvotes: 3
Reputation: 16566
You can do it through string:
>>> var1=2
>>> var2=4
>>> var3=float(str(var1)+"."+str(var2))
>>> var3
2.3999999999999999
Upvotes: 6