fork download
  1. #0JvQtdGJ0LXQvdC60L4=
  2. import numpy as np
  3.  
  4.  
  5. # 2
  6. print("\t<< task 2 >>")
  7. term = np.float32(1.);
  8. sum_val = np.float32(2.);
  9.  
  10. while(sum_val > np.float32(1.)):
  11. eps = term;
  12.  
  13. term /= np.float32(2.);
  14. sum_val = np.float32(1.) + term;
  15.  
  16. print(eps);
  17.  
  18. # 3
  19. print("\t<< task 3 >>")
  20. term = np.float64(1.);
  21. sum_val = np.float64(2.);
  22.  
  23. while(sum_val > np.float64(1.)):
  24. eps = term;
  25.  
  26. term /= np.float64(2.);
  27. sum_val = np.float64(1.) + term;
  28.  
  29. print(eps);
  30.  
  31. # 4
  32. print("\t<< task 4 >>")
  33. value = np.float32(8.8)
  34. epc = np.spacing(value)
  35. print(epc)
  36.  
  37. # 5
  38. print("\t<< task 5 >>")
  39. value = np.float64(8.8)
  40. epc = np.spacing(value)
  41. print(epc)
  42.  
  43. # 6
  44. print("\t<< task 6 >>")
  45. def solve_sqrt(target, tolerance):
  46. x = target / 2.0
  47. iterations = 0
  48.  
  49. while True:
  50. iterations += 1
  51. next_x = (x + target / x) / 2
  52.  
  53. if abs(next_x - x) < tolerance:
  54. return next_x, iterations
  55.  
  56. x = next_x
  57.  
  58. test_tolerances = [1e-1, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15]
  59. target_number = 7
  60.  
  61.  
  62.  
  63. for tol in test_tolerances:
  64. root, count = solve_sqrt(target_number, tol)
  65. print(f"{tol}\t{root}\t{count}")
  66.  
  67.  
  68.  
Success #stdin #stdout 1.06s 41380KB
stdin
Standard input is empty
stdout
	<< task 2 >>
1.1920929e-07
	<< task 3 >>
2.220446049250313e-16
	<< task 4 >>
9.536743e-07
	<< task 5 >>
1.7763568394002505e-15
	<< task 6 >>
0.1	2.6457520483808037	3
0.001	2.6457513110646933	4
1e-06	2.6457513110646933	4
1e-09	2.6457513110645907	5
1e-12	2.6457513110645907	5
1e-15	2.6457513110645907	6