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 次查看(过去 30 天)
显示 更早的评论
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 个评论
Guillaume
2016-5-24
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...
回答(3 个)
Walter Roberson
2016-5-24
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 个评论
Guillaume
2016-5-24
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
2016-5-24
编辑:Guillaume
2016-5-24
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 个评论
KSSV
2016-5-24
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 个评论
Guillaume
2016-5-24
Doh! That's what I meant. Fixed. My point still stand in that 1e-100 is completely useless in this case.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!