Python Forum

Full Version: code running for more than an hour now, yet didn't get any result, what should I do?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to implement a triple integral Riemann sum. My single and double integral codes are working. I just added the for k in range (1,l+1):, l = int(zb/dz) and za+(k-1)*dz in the code below. It's not getting any error nor results. It's just running. It's been more than an hour now. What other ways/code would you suggest as a replacement of the code below? Using math library only and has to implement the function calculate(f, xa, xb, ya, yb, za, zb). I'm still new to this just for your information. Thank you for all the help.


dx = 0.002
dy = 0.002
dz = 0.002

def calculate(f, xa, xb, ya, yb, za, zb):
  n = int(xb/dx)
  m = int(yb/dy)
  l = int(zb/dz)
  t = dx*dy*dz
  total = 0
  for i in range (1,n+1):
    for j in range (1,m+1):
      for k in range (1,l+1):
        total += f(xa+(i-1)*dx, ya+(j-1)*dy, za+(k-1)*dz)*t
  return total

def p(x, y, z):
  return math.sin(x) + math.cos(y) + math.tan(z)

s = calculate(p, 0, 3, 0, 2, 0, 1)
print("{:.3f}".format(s))
Why do you loop over range(1, i+1) and then subtract 1 from i?

This is not correct.
 n = int(xb/dx)
  m = int(yb/dy)
  l = int(zb/dz)
It is only correct if xa, ya and za are all zero.

I have no idea why it would take hours. I set dz = 1 and the program takes 1.3 seconds on my computer. I set dz = 0.2 and it took 5 times longer (5.3 seconds). I set dz = 0.02 and it took 10 times longer than that (50 seconds). I would expect dz = 0.002 should take 500 seconds. A long time to wait, but not hours.

For the function p this is a particularly inefficient way to compute the total. In your particular example cos(ya+(j-1)*dy) is computed for each iteration of the "k" loop. The value is the same each time. You are calling math.cos() 500 times more often then is needed, and you are calling math.sin() 500,000 times more often than is needed.
If you take dx = dy = dz = 0.02 it should be 1000 times faster already.