Proving distributive law with for loop

6 visualizaciones (últimos 30 días)
Brian Villeneuve
Brian Villeneuve el 19 de En. de 2016
Comentada: Roger Wohlwend el 21 de En. de 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 comentario
Guillaume
Guillaume el 20 de En. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

Roger Wohlwend
Roger Wohlwend el 20 de En. de 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 comentarios
Brian Villeneuve
Brian Villeneuve el 20 de En. de 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 el 21 de En. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by