I want to print the value of t when value of vc1 is 90.5931 but I am not able to do so. please help
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
for t1=0:0.00001:0.15
vc1 = 100-100*exp(-5000*t1)*(cosh(2000*6^(1/2)*t1) + ...
(5*6^(1/2)*sinh(2000*6^(1/2)*t1))/12);
while(vc1 == 90.5931)
display(t1)
end
plot(t1,vc1)
hold on
end
1 commentaire
Guillaume
le 24 Mai 2016
Note that you're actually lucky that your comparison didn't work as if it did, you would have entered a never ending loop
while vc1 == 90.5931
display(t1)
end
means: enter the loop if vc1 is equal to 90.5931, then display t1 and try the loop again. Since vc1 has not change, it will display t1 again and try again, and again...
Réponses (3)
Walter Roberson
le 24 Mai 2016
t1 =0:0.00001:0.15;
vc1 = 100 - 100*exp(-5000*t1) .* (cosh(2000*6^(1/2)*t1) + ...
(5*6^(1/2)*sinh(2000*6^(1/2)*t1))/12);
plot(t1, vc1);
tidx = find(vc1 >= 90.5931, 1, 'first');
t1(tidx)
1 commentaire
Guillaume
le 24 Mai 2016
I'm not convinced your tidx is the one the OP wants as this returns the t1 for ~90.603 which is the next one after ~90.5931.
Guillaume
le 24 Mai 2016
Modifié(e) : Guillaume
le 24 Mai 2016
As per Dr Siva's answer, do not use == to compare floating points numbers unless the two numbers have been obtained exactly the same way (both results of the same calculation or both typed in the code), due to floating point accuracy (the way numbers are actually stored and the round-off error of calculation).
Always compare the absolute difference of the number relative to an arbitrary small number. Some multiple of eps may be a good idea (the actual function not some made up variable with an unrealistic value), or just an arbitray small number. In your case, the actual value is around 2*1e-5 away from 90.5931, so I suggest using 1e-4
if abs(vc1 - 90.5931) < 1e-4 %with no eps variable existing
To answer your second problem, the slow plotting, the answer is not to use a loop:
t1 = 0 : 1e-5 : 0.15;
vc1 = 100 - 100*exp(-5000*t1) .* (cosh(2000*6^(1/2)*t1) + ...
(5*6^(1/2)*sinh(2000*6^(1/2)*t1))/12);
plot(t1, vc1, '.r');
%and to find for which t1, vc1 is near 90.5953:
t90 = t1(abs(vc1 - 90.5931) < 1e-4)
0 commentaires
KSSV
le 24 Mai 2016
Dont try to equate floating point numbers. Try the following:
eps = 10^-100 ; % Set a small number epsilon for equating
for t1 =0:0.00001:0.15
vc1 = 100-100*exp(-5000*t1)*(cosh(2000*6^(1/2)*t1) + ...
(5*6^(1/2)*sinh(2000*6^(1/2)*t1))/12);
if ((vc1 - 90.5931)< eps)
display(t1)
end
plot(t1,vc1,'.r')
drawnow
hold on
end
4 commentaires
Guillaume
le 24 Mai 2016
Doh! That's what I meant. Fixed. My point still stand in that 1e-100 is completely useless in this case.
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements 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!