Effacer les filtres
Effacer les filtres

Proving distributive law with for loop

5 vues (au cours des 30 derniers jours)
Brian Villeneuve
Brian Villeneuve le 19 Jan 2016
Commenté : Roger Wohlwend le 21 Jan 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 commentaire
Guillaume
Guillaume le 20 Jan 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.

Connectez-vous pour commenter.

Réponse acceptée

Roger Wohlwend
Roger Wohlwend le 20 Jan 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 commentaires
Brian Villeneuve
Brian Villeneuve le 20 Jan 2016
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 le 21 Jan 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by