How could I convert python code to matlab?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Guillaume
le 10 Avr 2018
Modifié(e) : Guillaume
le 10 Avr 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.
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 commentaires
Voir également
Catégories
En savoir plus sur Call Python from MATLAB dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!