Home > Blockchain >  Unable to properly increment variable in Python
Unable to properly increment variable in Python

Time:01-26

I am having an issue with my code. The increment in the last if statement doesn't properly increment. My main issue is that for frac and dfrac, I receive a value of zero, which I assume is because hit is being read as zero.

import LT.box as B
import numpy as np
import matplotlib.pyplot as plt
import sys
import math

#width (cm)
w = 15
#length (cm)
l = 20
#distance between panels (cm)
d = 80
#number of events
n = 10000

print('Width cm:', w)
print('Length cm:', l)
print('Distance cm:', d)
print('Number of events:', n)


hit = 0
for i in range(n):
    if i % 5000 == 0:
        print("Event m out of %d\r" % (i, n))
        sys.stdout.flush()

    # accepted number of rays
    cost = np.random.random()**(1/3)
    phi = np.random.random()*2.0*np.pi
    xtop =np.random.random()*w
    ytop = np.random.random()*l
    sinp = np.sin(phi)
    cosp = np.cos(phi)
    sint = np.sqrt(1.0 - cost*cost)
    tant = sint/cost
    tantx = tant*sinp
    tanty = tant*cosp
    xbot = xtop-tantx*d
    ybot = ytop-tanty*d

    # check if event goes through both panels
    if (0 <= xbot <= w) and (0 <= ybot <= l):
        if (w <= xbot d <= 2*w) and (0 <= ybot <= l):
            hit  =1

frac = hit / n
dfrac = math.sqrt(hit) / n

I tried making an increment function and other methods of incrementation, but I wasn't able to implement it. I either got the same value of zero in frac or I received a syntax error.

CodePudding user response:

The problem with the original code is that the two conditions set for xbot are incompatible. The first condition states that xbot must be between 0 and 15, while the second condition states that xbot 80 must be between 15 and 30. However, if a variable has a value between 0 and 15, adding 80 to it will never make it have a value between 15 and 30.

Here are the two conditions that xbot needs to satisfy, in order for hit to be incremented:

  1. 0 <= xbot <= 15
  2. 15 <= xbot 80 <= 30

If you analyze the lower and up bounds that the first condition requires, then the smallest value xbot can have is 0 and the maximum value is 15. If you add those bounds to the second condition, you would have:

  • For xbot = 0: 15 <= 80 <= 30 (FAILS)
  • For xbot = 15: 15 <= 95 <= 30 (FAILS)

Simply putting, if a variable has a value between 0 and 15, adding 80 to it will never make it have a value between 15 and 30.

Now, I don't know exactly what you're trying to achieve, but the simplest solution to your problem would be to either remove one of the conditions set to xbot, or find two conditions that are compatible:

    # ...
    # check if event goes through both panels
    if (0 <= xbot <= w) and (0 <= ybot <= l):
        hit  =1
    # ...
  • Related