Proving distributive law with for loop

7 次查看(过去 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
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
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 个评论
Brian Villeneuve
Brian Villeneuve 2016-1-20
The only issue with this is that an error code arises when inputting "f" and "g". The inner matrix dimensions do not agree
Roger Wohlwend
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!

Translated by