Search code examples
pythonmathematical-optimization

Calculate a value from randomly generated numbers which is always positive


I am trying to make sure that the value tDiscriminant is always positive. As you can see below, it is calculated from three randomly generated numbers.

s = random.uniform(1,100)
sRounded = round(s,1)   
v = random.uniform(1,50)
vRounded = round(v,1)   
a = random.uniform(1,20)
aRounded = round(a,1)
tDiscriminant = (vRounded*vRounded)-(2*aRounded*sRounded)
tDiscriminantRooted = math.sqrt(tDiscriminant)

How do I make it so that if tDiscriminant is negative, the values s, v and a have to be generated again until tDiscriminant is positive?


Solution

  • Try

    import random
    tDiscriminant = -1
    while tDiscriminant <= 0:
      s = random.uniform(1,400)
      sRounded = round(s,1)   
      v = random.uniform(1,50)
      vRounded = round(v,1)   
      a = random.uniform(1,20)
      aRounded = round(a,1)
      tDiscriminant = (vRounded*vRounded)-(2*aRounded*sRounded)
    tDiscriminantRooted = math.sqrt(tDiscriminant)