How could I convert python code to matlab?

조회 수: 1 (최근 30일)
LALE ASIK
LALE ASIK 2018년 4월 10일
편집: Guillaume 2018년 4월 10일
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()

답변 (1개)

Guillaume
Guillaume 2018년 4월 10일
편집: Guillaume 2018년 4월 10일
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.

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by