Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge two integer variables in a single float in python

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

like image 857
arcanavk Avatar asked Apr 08 '14 11:04

arcanavk


People also ask

Can you combine float and int in Python?

Integers and floating-point numbers can be mixed in arithmetic. Python 3 automatically converts integers to floats as needed.

How do you stick 2 numbers together in Python?

If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.

How do you print an int and a string in Python?

Use the syntax print(str(INT)) to return the int as a str , or string.


2 Answers

You can do it through string:

>>> var1=2
>>> var2=4
>>> var3=float(str(var1)+"."+str(var2))
>>> var3
2.3999999999999999
like image 130
fredtantini Avatar answered Sep 18 '22 00:09

fredtantini


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.

like image 43
Scorpion_God Avatar answered Sep 20 '22 00:09

Scorpion_God