How could I convert python code to matlab?
2 次查看(过去 30 天)
显示 更早的评论
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()
0 个评论
回答(1 个)
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.
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Call Python from MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!