user3784773
user3784773

Reputation: 185

Find the integer that is closest to the power of two

so I am trying to find the power of two that is nearest to n. For instance 10.5 is closer to 8 than 16. So far I know how to import math* for the log and ceil. I am not sure how to proceed.

Upvotes: 1

Views: 8402

Answers (4)

Yann Dubois
Yann Dubois

Reputation: 1345

In the case of integers, you can also check the second digit of the binary representation of the number.

def closest_power2(x):
    """
    Return the closest power of 2 by checking whether 
    the second binary number is a 1.
    """
    op = math.floor if bin(x)[3] != "1" else math.ceil
    return 2**(op(math.log(x,2)))

Upvotes: 3

Rohan Goyal
Rohan Goyal

Reputation: 11

You are given two numbers a and b. When a is raised to some power p, we get a number x. Now, you need to find what is the value of x that is closest to b.

#User function Template for python3

def nearestPower(a,b):
    high=100000  #any big number
    sum=1
    while True:
        sum=sum*a;
        if(abs(sum-b)<high):
            high=abs(sum-b)
            c=sum
        if(abs(sum-b)>high):
            break;
    return c

Upvotes: 0

koffein
koffein

Reputation: 1882

At first I create both possible outcomes/exponents and after that I use the min function, that returns the exponent with the closest power to x. The keyword-parameter key holds the function for measuring the distance between those two powers.

from math import log, ceil, floor
def closest_power(x):
    possible_results = floor(log(x, 2)), ceil(log(x, 2))
    return min(possible_results, key= lambda z: abs(x-2**z))

closest_power(11.5), closest_power(13.3)

Output

(3.0, 4.0)

Upvotes: 10

Scott Harris
Scott Harris

Reputation: 319

round(math.log(n, 2))

Might work.

Upvotes: 0

Related Questions