fork download
  1. from mpi4py import MPI
  2. import numpy as np
  3. import time
  4.  
  5. def trapezoidal_rule(func, a, b, n):
  6. h = (b - a) / n
  7. integral = (func(a) + func(b)) / 2.0
  8. for i in range(1, n):
  9. x_i = a + i * h
  10. integral += func(x_i)
  11. integral *= h
  12. return integral
  13.  
  14. def midpoint_rule(func, a, b, n):
  15. h = (b - a) / n
  16. integral = 0.0
  17. for i in range(n):
  18. x_mid = a + (i + 0.5) * h
  19. integral += func(x_mid)
  20. integral *= h
  21. return integral
  22.  
  23. if __name__ == "__main__":
  24. comm = MPI.COMM_WORLD
  25. rank = comm.Get_rank()
  26. size = comm.Get_size()
  27.  
  28. if rank == 0:
  29. # User input
  30. function_str = input("Enter the function (in terms of x): ")
  31. a = float(input("Enter the lower bound (a): "))
  32. b = float(input("Enter the upper bound (b): "))
  33. n_values = [int(input(f"Enter the number of intervals (n) for experiment {i+1}: ")) for i in range(3)]
  34. else:
  35. function_str = None
  36. a = None
  37. b = None
  38. n_values = [None] * 3
  39.  
  40. # Broadcast user input to all processes
  41. function_str = comm.bcast(function_str, root=0)
  42. a = comm.bcast(a, root=0)
  43. b = comm.bcast(b, root=0)
  44. n_values = comm.bcast(n_values, root=0)
  45.  
  46. # Parse the function string and create a function object
  47. def func_wrapper(x):
  48. return eval(function_str)
  49.  
  50. start_time = time.time()
  51.  
  52. for n in n_values:
  53. if rank == 0:
  54. print(f"Experiment with n = {n}:")
  55. local_n = n // size
  56. local_a = a + rank * (b - a) / size
  57. local_b = local_a + (b - a) / size
  58.  
  59. local_integral_trapezoidal = trapezoidal_rule(func_wrapper, local_a, local_b, local_n)
  60. local_integral_midpoint = midpoint_rule(func_wrapper, local_a, local_b, local_n)
  61.  
  62. integral_trapezoidal = comm.reduce(local_integral_trapezoidal, op=MPI.SUM, root=0)
  63. integral_midpoint = comm.reduce(local_integral_midpoint, op=MPI.SUM, root=0)
  64.  
  65. if rank == 0:
  66. end_time = time.time()
  67. print("Trapezoidal Rule:")
  68. print(f" Computed Integral: {integral_trapezoidal}")
  69. print(f" Time taken: {end_time - start_time} seconds")
  70. print("Midpoint Rule:")
  71. print(f" Computed Integral: {integral_midpoint}")
  72. print(f" Time taken: {end_time - start_time} seconds")
  73.  
  74. MPI.Finalize()
Success #stdin #stdout #stderr 0.3s 40348KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "from mpi4py"
Execution halted