Filter löschen
Filter löschen

How could I convert python code to matlab?

2 Ansichten (letzte 30 Tage)
LALE ASIK
LALE ASIK am 10 Apr. 2018
Bearbeitet: Guillaume am 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()

Antworten (1)

Guillaume
Guillaume am 10 Apr. 2018
Bearbeitet: Guillaume am 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.

Kategorien

Mehr zu Call Python from MATLAB finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by