Paolo Lorenzini
Paolo Lorenzini

Reputation: 725

conversion of function from Matlab to python

I have a MATLAB function :

Bits=30
NBits= ceil(fzero(@(x)2^(x) - x -1 - Bits, max(log2(Bits),1)))

I want to convert it to python, I wrote something like this so far:

from numpy import log, log2
from scipy.optimize import root_scalar

def func(x,Bits):
    return ((x)2^(x)-x-1-Bits, max(log2(Bits)))

However it says that it need to be (x)*2^ Does anybody know first, if the conversion from Matlab to python is correct? and second if * has to be added?

Upon suggestion I wrote this lambda function:

lambda x: (2^(x) -x -1 -Bits) , max(log2(Bits))

but I get this error: TypeError: 'numpy.float64' object is not iterable

Upvotes: 0

Views: 241

Answers (1)

scotty3785
scotty3785

Reputation: 7006

I don't have numpy or scipy on this computer so here is my best attempt at an answer.

def YourFunc(Bits):
    return math.ceil(root_scalar(lambda x: (2**x)-x-1-Bits, x0 = max(log2(Bits),1)))

Bits = 30
NBits = YourFunc(30)

print(NBits)

I used this function for log2 rather than the one from numpy. Try it

def log2(x):
    return math.log(x,2)

Upvotes: 2

Related Questions