How could I convert python code to matlab?

2 views (last 30 days)
LALE ASIK
LALE ASIK on 10 Apr 2018
Edited: Guillaume on 10 Apr 2018
I have the following python code that I would like to convert to Matlab code. Could anyone help me how to do this?
#floating point epsilon (for floating point comparisons)
fep = .000000001
# tests if there is a rational number with denominator less than max_denom that is within tolerance of num
def seems_rational(num,tol,max_denom):
#the number to check against as a reference
ref = float(num)
for denom in range(1,max_denom+1):
#works for checking against numbers less than or equal to 1. (the upper triangular part of the matrix) since numerator is less than or equal to denominator
for numer in range(1, denom+1):
test = float(numer)/float(denom)
error = abs(test-ref)
if error<=tol+fep:
print str(numer) + "/" + str(denom)
return True
return False
f = open("testdata.csv","r")
is_rational = True
for l in f:
#cutoff the newline character
#change the parameters in this function call to chance tolerance and max denominator
if not seems_rational(l[:len(l)-1],.0001,50):
print l[:len(l)-1] + " doesn't seem rational"
is_rational = False
#break
print "All Rational?: " + str(is_rational)
f.close()

Answers (1)

Guillaume
Guillaume on 10 Apr 2018
Edited: Guillaume on 10 Apr 2018
Eeek! That's not an efficient algorithm. There are much better algorithms for that. Worse is the use of fep on top on the tolerance which shows that somebody has not understood floating point comparison at all.
Anyway, why bother implementing your own algorithm when matlab has rat
function tf = seems_rational(num, tol, max_denom)
[n, d] = rat(num, tol);
tf = d <= max_denom;
end
As a bonus, the above also works for numbers > 1 unlike the python code.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!