Proving distributive law with for loop
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Brian Villeneuve
il 19 Gen 2016
Commentato: Roger Wohlwend
il 21 Gen 2016
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 Commento
Guillaume
il 20 Gen 2016
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.
Risposta accettata
Roger Wohlwend
il 20 Gen 2016
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 Commenti
Roger Wohlwend
il 21 Gen 2016
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.
Più risposte (0)
Vedere anche
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!