Proving distributive law with for loop
조회 수: 6 (최근 30일)
이전 댓글 표시
Trying to prove distributive law... x*(y+z)=xy+xz, I want to run a loop 10,000 times, drawing 3 random numbers on interval (0,1) and then check if the law holds. So far what I have is:
x=rand()
y=rand()
z=rand()
f=x*(y+z)
g=(x*y)+(x*z)
for k=1:10000
k
if f~=g
disp ('FALSE')
end
I want to see each iteration so that I can note which combination of numbers for variables x,y,z makes the test fail.
If there is a way to also count how many times the test fails and provide an average that would be useful as well. Any help is greatly appreciated!
댓글 수: 1
Guillaume
2016년 1월 20일
Note that in the code you've posted, you're doing 10,000 times the same comparison.
If your computer does not give you the exact same output for each of them, you've got a problem!
Now, if you moved the random number generation into the loop, that would be more interesting.
채택된 답변
Roger Wohlwend
2016년 1월 20일
You can do it without a Loop! You should do it without a Loop!
n = 10000;
x=rand(n,1);
y=rand(n,1);
z=rand(n,1);
f=x*(y+z)
g=(x*y)+(x*z)
q = abs(f - g) > eps;
The vector q tells you now where the test Fails. If you want to know the rows where the test Fails, use
find(q)
If you want to know how many times the test failed:
sum(q)
The average is
sum(q) / n
댓글 수: 2
Roger Wohlwend
2016년 1월 21일
Instead of
f = x * (y+z)
g = (x*y) + (x*z)
write
f = x.*(y + Z)
g = (x.*y) + (x.*z)
and the error vanishes.
추가 답변 (0개)
참고 항목
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!