ROLLIN40SCRIPS
ROLLIN40SCRIPS

Reputation: 21

What does the print mean and its execution?

Can someone help me understand what this code does? The task is that I need to describe what the program does and what the print tells us. I'm really stuck and could use some help!

from random import random

wrong = 0; N = 100000

for i in range(N):
    x = random(); y = random(); z = random()
    res1 = (x + y) * z
    res2 = x*z + y*z
    if res1 != res2:
        wrong += 1
        x0 = x; y0 = y; z0 = z
        notequal1 = res1
        notequal2 = res2

print (100. * wrong/N)
print (x0, y0, z0, notequal1 - notequal2)¨

the code prints out:

30.825
0.7274024508251914 0.7713456905186189 0.06463959172321276 1.3877787807814457e-17

Upvotes: 0

Views: 31

Answers (1)

prasys
prasys

Reputation: 23

Basically what your code does is simple

For 100000 times , it does the following :-

  1. It generates 3 random numbers
  2. It performs two operations (one is adding x and y and then multiplying by z. The other one multiplies x with z and y with z
  3. Then it performs a comparison if both are not equal or not . If they are not equal , then it increases the counter (aka number of times wrong) by 1 and then stores the value

Lastly , once it has executed 100000 times , it prints out the percentage of wrong (how many times in that run it was wrong aka not equal) and also what were the last value and the differences

Hope this helps you out in understanding the code.

Upvotes: 1

Related Questions