Problem with IF statement

why doesn't it give me a result if I enter " if D == l " I wan't to calculate all initial velocities and angles at which the length is 100m.
clear all
close all
clc
%1
v0 = [15:0.001:60]; %initial velocity
kot = [15:60]; %angle
g = 9.81; %gravity
l = 100; %distance
for i = 1:length(v0)
for j = 1:length(kot)
D = (v0(i)^2*sind(2*kot(j)))/g; %distance
if D == l
fprintf('Vo = %.2f m/s | kot = %.2f° | D = %.2f \n',v0(i),kot(j), D);
end
end
end

回答 (1 件)

Rik
Rik 2020 年 11 月 27 日

0 投票

Don't use clear all. You don't need it.
I suspect you encountered the wondrous world of floats. Computers don't have infinite memory and may round numbers in ways that you don't expect. This is especially a problem if you are asking for exact equality, while you would be satisfied with equality within machine precision.
Instead of a==b use abs(a-b)<tol. You can use the eps function, or set another value.

4 件のコメント

Fe99
Fe99 2020 年 11 月 27 日
This don’t help but thanks anyway.
Rik
Rik 2020 年 11 月 27 日
Why not? Using the code below you can find how close D gets to 100. So if you pick a tolerance that is above that, your code will print.
v0 = 15:0.001:60; %initial velocity
kot = 15:60; %angle
g = 9.81; %gravity
l = 100; %distance
[i,j] = meshgrid(1:length(v0),1:length(kot));
D = (v0(i).^2.*sind(2*kot(j)))/g; %distance
smallest_diff=min(abs(D(:)-100))
smallest_diff = 4.0932e-05
%repeat your code, but with the edits I described
tol=5e-5;
for i = 1:length(v0)
for j = 1:length(kot)
D = (v0(i)^2*sind(2*kot(j)))/g; %distance
if abs(D-l)<tol
fprintf('Vo = %.2f m/s | kot = %.2f° | D = %.2f \n',v0(i),kot(j), D);
end
end
end
Vo = 36.93 m/s | kot = 23.00° | D = 100.00
Fe99
Fe99 2020 年 11 月 27 日
sorry my bad. thanks for answer
Rik
Rik 2020 年 11 月 27 日
No problem. If my answer solved your question, please consider marking my answer as accepted answer. If not, feel free to comment with your remaining issues.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeProgramming についてさらに検索

タグ

質問済み:

2020 年 11 月 27 日

コメント済み:

Rik
2020 年 11 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by