From a56525855cf0030de0ac2374146ebfb67df778cf Mon Sep 17 00:00:00 2001 From: avivfaraj <73610201+avivfaraj@users.noreply.github.com> Date: Fri, 3 Sep 2021 19:47:55 -0400 Subject: [PATCH 01/45] Add files via upload --- physics/gamma_function.py | 83 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 physics/gamma_function.py diff --git a/physics/gamma_function.py b/physics/gamma_function.py new file mode 100644 index 000000000000..395968aeb99b --- /dev/null +++ b/physics/gamma_function.py @@ -0,0 +1,83 @@ +""" +Gamma function is a very useful tool in physics. +It helps calculating complex integral in a convenient way. +for more info: https://en.wikipedia.org/wiki/Gamma_function +""" + +# Importing packages +from math import sqrt, pi +from re import match +from typing import Union + + +def gamma(num : Union[int, float]) -> Union[int, float]: + """ + Calculates the value of Gamma function of num + where num is either an integer (1,2,3..) or a half-integer (0.5,1.5,2.5...). + Implemented using recursion + Examples: + >>> Gamma of: 0.5 + √π + >>> Gamma of: 2 + 1 + >>> Gamma of: 3.5 + 1.875√π + """ + if num == 1: + return 1 + elif num == 0.5: + return sqrt(pi) + elif num > 1: + return (num - 1) * gamma(num - 1) + else: + # Error + return -2 + + +def test_gamma() -> None: + """ + >>> test_gamma() + """ + assert sqrt(pi) == gamma(0.5) + assert 1 == gamma(1) + assert 1 == gamma(2) + + +if __name__ == "__main__": + # Initialize boolean + number = True + # Get input from user + input_ = input("Gamma of: ") + # Ensure valid input + try: + # Ensure input matches half-integer (float) pattern + if match(r'^[0-9]*\.5$', input_): + # Convert string to float + num = float(input_) + # Ensure input matches an integer pattern + elif match(r'^[1-9][0-9]*$', input_): + # Convert string to int + num = int(input_) + # Input is not a valid number + else: + # raise an error + raise ValueError + # Ensure print an error message + except ValueError: + print("Invalid input: Must be an integer or an half-integer!") + number = False + finally: + # Ensure input is a valid number + if number: + # Ensure input is an integer + if (isinstance(gamma(num), int)): + # Print result + print(gamma(num)) + # Otherwise print results with √π (gamma of 0.5 is √π) + # Therefore all results will be a number times √π + else: + results = "{result:.4f}".format(result=gamma(num) / sqrt(pi)) + results = results.rstrip('0').rstrip('.') + if results == "1": + results = "" + print(results + "\u221A\u03c0") From 4951686999339c82012f6f9f6004c8ad7b918482 Mon Sep 17 00:00:00 2001 From: avivfaraj <73610201+avivfaraj@users.noreply.github.com> Date: Sat, 4 Sep 2021 10:19:15 -0400 Subject: [PATCH 02/45] Changed print to f-string Also printed out results in a math notation --- physics/gamma_function.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/physics/gamma_function.py b/physics/gamma_function.py index 395968aeb99b..bbef623408e7 100644 --- a/physics/gamma_function.py +++ b/physics/gamma_function.py @@ -64,11 +64,12 @@ def test_gamma() -> None: raise ValueError # Ensure print an error message except ValueError: - print("Invalid input: Must be an integer or an half-integer!") + print("Error: Input must be an integer or an half-integer!") number = False finally: # Ensure input is a valid number if number: + print(f"\u0393({num}) = ", end="") # Ensure input is an integer if (isinstance(gamma(num), int)): # Print result @@ -76,7 +77,7 @@ def test_gamma() -> None: # Otherwise print results with √π (gamma of 0.5 is √π) # Therefore all results will be a number times √π else: - results = "{result:.4f}".format(result=gamma(num) / sqrt(pi)) + results = f"{gamma(num) / sqrt(pi):.4f}" results = results.rstrip('0').rstrip('.') if results == "1": results = "" From ff2a162bddfb46e75a4020d5212efef684dd5850 Mon Sep 17 00:00:00 2001 From: avivfaraj <73610201+avivfaraj@users.noreply.github.com> Date: Sat, 4 Sep 2021 12:41:26 -0400 Subject: [PATCH 03/45] Add files via upload --- physics/horizontal_projectile_motion.py | 131 ++++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 physics/horizontal_projectile_motion.py diff --git a/physics/horizontal_projectile_motion.py b/physics/horizontal_projectile_motion.py new file mode 100644 index 000000000000..a5b2cff28fc1 --- /dev/null +++ b/physics/horizontal_projectile_motion.py @@ -0,0 +1,131 @@ +""" +Horizontal Projectile Motion problem in physics. +This algorithm solves a specific problem in which +the motion starts from the ground as can be seen below: + (v = 0) + ** + * * + * * + * * + * * + * * +GROUND GROUND + +For more info: https://en.wikipedia.org/wiki/Projectile_motion +""" + +# Importing packages +from math import pi, sin + +# Acceleration Constant on hearth (unit m/s^2) +g = 9.80665 + + +def angle_to_radians(angle): + """ + Convert an angle from degrees to randians + """ + return angle * pi / 180 + + +def horizontal_distance(init_velocity: float, angle: float) -> float: + """ + Returns the horizontal distance that the object cover + + Formula: + v_0^2 * sin(2 * alpha) + --------------------- + g + + v_0 - initial velocity + alpha - angle + + >>> horizontal_distance(30, 45) + 91.77 + >>> horizontal_distance(100, 78) + 414.76 + """ + radians = angle_to_radians(2 * angle) + return round((init_velocity ** 2) * sin(radians) / g, 2) + + +def max_height(init_velocity: float, angle: float) -> float: + """ + Returns the maximum height that the object reach + + Formula: + v_0^2 * sin^2(alpha) + -------------------- + 2g + + v_0 - initial velocity + alpha - angle + + >>> max_height(30, 45) + 22.94 + >>> max_height(100, 78) + 487.82 + """ + + radians = angle_to_radians(angle) + return round(((init_velocity ** 2) * (sin(radians)) ** 2) / (2 * g), 2) + + +def total_time(init_velocity: float, angle: float) -> float: + """ + Returns total time of the motion + + Formula: + 2 * v_0 * sin(alpha) + -------------------- + g + + v_0 - initial velocity + alpha - angle + + >>> total_time(30, 45) + 4.33 + >>> total_time(100, 78) + 19.95 + """ + + radians = angle_to_radians(angle) + return round((2 * init_velocity) * (sin(radians)) / g, 2) + + +def test_motion() -> None: + """ + >>> test_motion() + """ + v0, angle = 25, 20 + assert 40.97 == horizontal_distance(v0, angle) + assert 3.73 == max_height(v0, angle) + assert 1.74 == total_time(v0, angle) + + +if __name__ == "__main__": + + # Get input from user + init_vel = float(input("Initial Velocity: ")) + + # Get input from user + angle = float(input("angle: ")) + + # Ensure valid angle + if angle > 90 or angle <= 0: + print("Error: Invalid angle. Range is 1-90 degrees.") + + # Ensure valid velocity + elif init_vel < 0: + print("Error: Invalid velocity. Should be a positive number.") + + # Print results + else: + print() + h_dis = str(horizontal_distance(init_vel, angle)) + v_dis = str(max_height(init_vel, angle)) + t_time = str(total_time(init_vel, angle)) + print("Results: ") + print("Horizontal Distance: " + h_dis + " [m]") + print("Maximum Height: " + v_dis + " [m]") + print("Total Time: " + t_time + " [s]") From 6550183d999e2a4a149790e40de6d536c2d509dd Mon Sep 17 00:00:00 2001 From: avivfaraj <73610201+avivfaraj@users.noreply.github.com> Date: Sat, 4 Sep 2021 12:53:35 -0400 Subject: [PATCH 04/45] Fixes: #4710 provided return type --- physics/horizontal_projectile_motion.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/physics/horizontal_projectile_motion.py b/physics/horizontal_projectile_motion.py index a5b2cff28fc1..09a0d07489e8 100644 --- a/physics/horizontal_projectile_motion.py +++ b/physics/horizontal_projectile_motion.py @@ -21,7 +21,7 @@ g = 9.80665 -def angle_to_radians(angle): +def angle_to_radians(angle : float) -> float: """ Convert an angle from degrees to randians """ From 552546f2c1e07587366b88b36b71b912c730f3a3 Mon Sep 17 00:00:00 2001 From: avivfaraj <73610201+avivfaraj@users.noreply.github.com> Date: Sat, 4 Sep 2021 12:55:13 -0400 Subject: [PATCH 05/45] File exists in another pull request --- physics/gamma_function.py | 84 --------------------------------------- 1 file changed, 84 deletions(-) delete mode 100644 physics/gamma_function.py diff --git a/physics/gamma_function.py b/physics/gamma_function.py deleted file mode 100644 index bbef623408e7..000000000000 --- a/physics/gamma_function.py +++ /dev/null @@ -1,84 +0,0 @@ -""" -Gamma function is a very useful tool in physics. -It helps calculating complex integral in a convenient way. -for more info: https://en.wikipedia.org/wiki/Gamma_function -""" - -# Importing packages -from math import sqrt, pi -from re import match -from typing import Union - - -def gamma(num : Union[int, float]) -> Union[int, float]: - """ - Calculates the value of Gamma function of num - where num is either an integer (1,2,3..) or a half-integer (0.5,1.5,2.5...). - Implemented using recursion - Examples: - >>> Gamma of: 0.5 - √π - >>> Gamma of: 2 - 1 - >>> Gamma of: 3.5 - 1.875√π - """ - if num == 1: - return 1 - elif num == 0.5: - return sqrt(pi) - elif num > 1: - return (num - 1) * gamma(num - 1) - else: - # Error - return -2 - - -def test_gamma() -> None: - """ - >>> test_gamma() - """ - assert sqrt(pi) == gamma(0.5) - assert 1 == gamma(1) - assert 1 == gamma(2) - - -if __name__ == "__main__": - # Initialize boolean - number = True - # Get input from user - input_ = input("Gamma of: ") - # Ensure valid input - try: - # Ensure input matches half-integer (float) pattern - if match(r'^[0-9]*\.5$', input_): - # Convert string to float - num = float(input_) - # Ensure input matches an integer pattern - elif match(r'^[1-9][0-9]*$', input_): - # Convert string to int - num = int(input_) - # Input is not a valid number - else: - # raise an error - raise ValueError - # Ensure print an error message - except ValueError: - print("Error: Input must be an integer or an half-integer!") - number = False - finally: - # Ensure input is a valid number - if number: - print(f"\u0393({num}) = ", end="") - # Ensure input is an integer - if (isinstance(gamma(num), int)): - # Print result - print(gamma(num)) - # Otherwise print results with √π (gamma of 0.5 is √π) - # Therefore all results will be a number times √π - else: - results = f"{gamma(num) / sqrt(pi):.4f}" - results = results.rstrip('0').rstrip('.') - if results == "1": - results = "" - print(results + "\u221A\u03c0") From bc31e3fa7160f11b98d4dcca50c7e89faf61480b Mon Sep 17 00:00:00 2001 From: avivfaraj <73610201+avivfaraj@users.noreply.github.com> Date: Sun, 5 Sep 2021 12:56:31 -0400 Subject: [PATCH 06/45] imported radians from math --- physics/horizontal_projectile_motion.py | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/physics/horizontal_projectile_motion.py b/physics/horizontal_projectile_motion.py index 09a0d07489e8..89d6f635f6e5 100644 --- a/physics/horizontal_projectile_motion.py +++ b/physics/horizontal_projectile_motion.py @@ -15,19 +15,12 @@ """ # Importing packages -from math import pi, sin +from math import pi, sin, radians as angle_to_radians # Acceleration Constant on hearth (unit m/s^2) g = 9.80665 -def angle_to_radians(angle : float) -> float: - """ - Convert an angle from degrees to randians - """ - return angle * pi / 180 - - def horizontal_distance(init_velocity: float, angle: float) -> float: """ Returns the horizontal distance that the object cover From 974e0a6e9561b145631fcbabb6b036be4485966e Mon Sep 17 00:00:00 2001 From: Aviv Faraj <73610201+avivfaraj@users.noreply.github.com> Date: Mon, 6 Sep 2021 13:08:33 -0400 Subject: [PATCH 07/45] Updated file according to pre-commit test --- physics/horizontal_projectile_motion.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/physics/horizontal_projectile_motion.py b/physics/horizontal_projectile_motion.py index 89d6f635f6e5..7147da1949a5 100644 --- a/physics/horizontal_projectile_motion.py +++ b/physics/horizontal_projectile_motion.py @@ -15,7 +15,9 @@ """ # Importing packages -from math import pi, sin, radians as angle_to_radians +from math import pi +from math import radians as angle_to_radians +from math import sin # Acceleration Constant on hearth (unit m/s^2) g = 9.80665 From 1d4fc814fac69ecd821559b0a540f4eea588b922 Mon Sep 17 00:00:00 2001 From: Username Date: Mon, 6 Sep 2021 13:16:58 -0400 Subject: [PATCH 08/45] Updated file --- maths/gamma_recursive.py | 83 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 maths/gamma_recursive.py diff --git a/maths/gamma_recursive.py b/maths/gamma_recursive.py new file mode 100644 index 000000000000..11c14c2cb2a3 --- /dev/null +++ b/maths/gamma_recursive.py @@ -0,0 +1,83 @@ +""" +Gamma function is a very useful tool in physics. +It helps calculating complex integral in a convenient way. +for more info: https://en.wikipedia.org/wiki/Gamma_function +""" + +# Importing packages +from math import sqrt, pi +from re import match +from typing import Union + + +def gamma(num : Union[int, float]) -> Union[int, float]: + """ + Calculates the value of Gamma function of num + where num is either an integer (1,2,3..) or a half-integer (0.5,1.5,2.5...). + Implemented using recursion + Examples: + >>> Gamma of: 0.5 + √π + >>> Gamma of: 2 + 1 + >>> Gamma of: 3.5 + 1.875√π + """ + if num == 1: + return 1 + elif num == 0.5: + return sqrt(pi) + elif num > 1: + return (num - 1) * gamma(num - 1) + # Error + return -2 + + +def test_gamma() -> None: + """ + >>> test_gamma() + """ + assert sqrt(pi) == gamma(0.5) + assert 1 == gamma(1) + assert 1 == gamma(2) + + +if __name__ == "__main__": + # Initialize boolean + number = True + # Get input from user + input_ = input("Gamma of: ") + # Ensure valid input + try: + # Ensure input matches half-integer (float) pattern + if match(r"^[0-9]*\.5$", input_): + # Convert string to float + num = float(input_) + # Ensure input matches an integer pattern + elif match(r"^[1-9][0-9]*$", input_): + # Convert string to int + num = int(input_) + # Input is not a valid number + else: + # raise an error + raise ValueError + # Ensure print an error message + except ValueError: + print("Error: Input must be an integer or an half-integer!") + number = False + finally: + # Ensure input is a valid number + if number: + print(f"\u0393({num}) = ", end="") + # Ensure input is an integer + if isinstance(gamma(num), int): + # Print result + print(gamma(num)) + # Otherwise print results with √π (gamma of 0.5 is √π) + # Therefore all results will be a number times √π + else: + results = f"{gamma(num) / sqrt(pi):.4f}" + results = results.rstrip("0").rstrip(".") + if results == "1": + results = "" + print(results + "\u221A\u03c0") \ No newline at end of file From 7bd84b4eee7aa118edff8aba79bf7130b099bd8b Mon Sep 17 00:00:00 2001 From: Username Date: Mon, 6 Sep 2021 13:55:20 -0400 Subject: [PATCH 09/45] Updated gamma --- maths/gamma_recursive.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/maths/gamma_recursive.py b/maths/gamma_recursive.py index 11c14c2cb2a3..e7e2c70c7ebe 100644 --- a/maths/gamma_recursive.py +++ b/maths/gamma_recursive.py @@ -5,12 +5,12 @@ """ # Importing packages -from math import sqrt, pi +from math import pi, sqrt from re import match from typing import Union -def gamma(num : Union[int, float]) -> Union[int, float]: +def gamma(num: Union[int, float]) -> Union[int, float]: """ Calculates the value of Gamma function of num where num is either an integer (1,2,3..) or a half-integer (0.5,1.5,2.5...). @@ -80,4 +80,4 @@ def test_gamma() -> None: results = results.rstrip("0").rstrip(".") if results == "1": results = "" - print(results + "\u221A\u03c0") \ No newline at end of file + print(results + "\u221A\u03c0") From 2841c11da1cac9d5e94dd72f6cd301561baad012 Mon Sep 17 00:00:00 2001 From: Aviv Faraj <73610201+avivfaraj@users.noreply.github.com> Date: Mon, 6 Sep 2021 13:58:46 -0400 Subject: [PATCH 10/45] Deleted duplicate file --- maths/gamma_recursive.py | 83 ---------------------------------------- 1 file changed, 83 deletions(-) delete mode 100644 maths/gamma_recursive.py diff --git a/maths/gamma_recursive.py b/maths/gamma_recursive.py deleted file mode 100644 index e7e2c70c7ebe..000000000000 --- a/maths/gamma_recursive.py +++ /dev/null @@ -1,83 +0,0 @@ -""" -Gamma function is a very useful tool in physics. -It helps calculating complex integral in a convenient way. -for more info: https://en.wikipedia.org/wiki/Gamma_function -""" - -# Importing packages -from math import pi, sqrt -from re import match -from typing import Union - - -def gamma(num: Union[int, float]) -> Union[int, float]: - """ - Calculates the value of Gamma function of num - where num is either an integer (1,2,3..) or a half-integer (0.5,1.5,2.5...). - Implemented using recursion - Examples: - >>> Gamma of: 0.5 - √π - >>> Gamma of: 2 - 1 - >>> Gamma of: 3.5 - 1.875√π - """ - if num == 1: - return 1 - elif num == 0.5: - return sqrt(pi) - elif num > 1: - return (num - 1) * gamma(num - 1) - # Error - return -2 - - -def test_gamma() -> None: - """ - >>> test_gamma() - """ - assert sqrt(pi) == gamma(0.5) - assert 1 == gamma(1) - assert 1 == gamma(2) - - -if __name__ == "__main__": - # Initialize boolean - number = True - # Get input from user - input_ = input("Gamma of: ") - # Ensure valid input - try: - # Ensure input matches half-integer (float) pattern - if match(r"^[0-9]*\.5$", input_): - # Convert string to float - num = float(input_) - # Ensure input matches an integer pattern - elif match(r"^[1-9][0-9]*$", input_): - # Convert string to int - num = int(input_) - # Input is not a valid number - else: - # raise an error - raise ValueError - # Ensure print an error message - except ValueError: - print("Error: Input must be an integer or an half-integer!") - number = False - finally: - # Ensure input is a valid number - if number: - print(f"\u0393({num}) = ", end="") - # Ensure input is an integer - if isinstance(gamma(num), int): - # Print result - print(gamma(num)) - # Otherwise print results with √π (gamma of 0.5 is √π) - # Therefore all results will be a number times √π - else: - results = f"{gamma(num) / sqrt(pi):.4f}" - results = results.rstrip("0").rstrip(".") - if results == "1": - results = "" - print(results + "\u221A\u03c0") From cea2deb0c8348f91cd566f327a3468fcfd98beec Mon Sep 17 00:00:00 2001 From: Aviv Faraj <73610201+avivfaraj@users.noreply.github.com> Date: Mon, 6 Sep 2021 13:59:46 -0400 Subject: [PATCH 11/45] removed pi --- physics/horizontal_projectile_motion.py | 1 - 1 file changed, 1 deletion(-) diff --git a/physics/horizontal_projectile_motion.py b/physics/horizontal_projectile_motion.py index 7147da1949a5..7ec370579810 100644 --- a/physics/horizontal_projectile_motion.py +++ b/physics/horizontal_projectile_motion.py @@ -15,7 +15,6 @@ """ # Importing packages -from math import pi from math import radians as angle_to_radians from math import sin From db7db3b3709ccb0b9c5a34e1b381b4b2693906f5 Mon Sep 17 00:00:00 2001 From: Aviv Faraj <73610201+avivfaraj@users.noreply.github.com> Date: Tue, 7 Sep 2021 09:31:36 -0400 Subject: [PATCH 12/45] reversed tests --- physics/horizontal_projectile_motion.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/physics/horizontal_projectile_motion.py b/physics/horizontal_projectile_motion.py index 7ec370579810..551c4089cd95 100644 --- a/physics/horizontal_projectile_motion.py +++ b/physics/horizontal_projectile_motion.py @@ -92,9 +92,9 @@ def test_motion() -> None: >>> test_motion() """ v0, angle = 25, 20 - assert 40.97 == horizontal_distance(v0, angle) - assert 3.73 == max_height(v0, angle) - assert 1.74 == total_time(v0, angle) + assert horizontal_distance(v0, angle) == 40.97 + assert max_height(v0, angle) == 3.73 + assert total_time(v0, angle) == 1.74 if __name__ == "__main__": From 132e4952ee8f20aebcd1b02232f38c3103c4906d Mon Sep 17 00:00:00 2001 From: Aviv Faraj <73610201+avivfaraj@users.noreply.github.com> Date: Tue, 7 Sep 2021 09:32:55 -0400 Subject: [PATCH 13/45] Fixed angle condition --- physics/horizontal_projectile_motion.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/physics/horizontal_projectile_motion.py b/physics/horizontal_projectile_motion.py index 551c4089cd95..ea90b5603771 100644 --- a/physics/horizontal_projectile_motion.py +++ b/physics/horizontal_projectile_motion.py @@ -106,7 +106,7 @@ def test_motion() -> None: angle = float(input("angle: ")) # Ensure valid angle - if angle > 90 or angle <= 0: + if angle > 90 or angle < 1: print("Error: Invalid angle. Range is 1-90 degrees.") # Ensure valid velocity From c0e5071e797e0621ce0034111d48514f4d3b929b Mon Sep 17 00:00:00 2001 From: Aviv Faraj <73610201+avivfaraj@users.noreply.github.com> Date: Tue, 7 Sep 2021 09:35:30 -0400 Subject: [PATCH 14/45] Modified prints to f-string --- physics/horizontal_projectile_motion.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/physics/horizontal_projectile_motion.py b/physics/horizontal_projectile_motion.py index ea90b5603771..96afc92b2241 100644 --- a/physics/horizontal_projectile_motion.py +++ b/physics/horizontal_projectile_motion.py @@ -120,6 +120,6 @@ def test_motion() -> None: v_dis = str(max_height(init_vel, angle)) t_time = str(total_time(init_vel, angle)) print("Results: ") - print("Horizontal Distance: " + h_dis + " [m]") - print("Maximum Height: " + v_dis + " [m]") - print("Total Time: " + t_time + " [s]") + print(f"Horizontal Distance: {h_dis} [m]") + print(f"Maximum Height: {v_dis} [m]") + print(f"Total Time: {t_time} [s]") From 894fa7f0098efc67592b4eb0d7aac068790f1657 Mon Sep 17 00:00:00 2001 From: Aviv Faraj <73610201+avivfaraj@users.noreply.github.com> Date: Tue, 7 Sep 2021 09:37:33 -0400 Subject: [PATCH 15/45] Update horizontal_projectile_motion.py --- physics/horizontal_projectile_motion.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/physics/horizontal_projectile_motion.py b/physics/horizontal_projectile_motion.py index 96afc92b2241..0ae6348ea5e5 100644 --- a/physics/horizontal_projectile_motion.py +++ b/physics/horizontal_projectile_motion.py @@ -116,10 +116,7 @@ def test_motion() -> None: # Print results else: print() - h_dis = str(horizontal_distance(init_vel, angle)) - v_dis = str(max_height(init_vel, angle)) - t_time = str(total_time(init_vel, angle)) print("Results: ") - print(f"Horizontal Distance: {h_dis} [m]") - print(f"Maximum Height: {v_dis} [m]") - print(f"Total Time: {t_time} [s]") + print(f"Horizontal Distance: {str(horizontal_distance(init_vel, angle))} [m]") + print(f"Maximum Height: {str(max_height(init_vel, angle))} [m]") + print(f"Total Time: {str(total_time(init_vel, angle))} [s]") From 07646ac92b6510e595c20211f374af8fc7e97df2 Mon Sep 17 00:00:00 2001 From: Aviv Faraj <73610201+avivfaraj@users.noreply.github.com> Date: Tue, 7 Sep 2021 14:41:47 -0400 Subject: [PATCH 16/45] Update horizontal_projectile_motion.py --- physics/horizontal_projectile_motion.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/physics/horizontal_projectile_motion.py b/physics/horizontal_projectile_motion.py index 0ae6348ea5e5..1fb02f42cc2a 100644 --- a/physics/horizontal_projectile_motion.py +++ b/physics/horizontal_projectile_motion.py @@ -21,7 +21,6 @@ # Acceleration Constant on hearth (unit m/s^2) g = 9.80665 - def horizontal_distance(init_velocity: float, angle: float) -> float: """ Returns the horizontal distance that the object cover @@ -40,7 +39,7 @@ def horizontal_distance(init_velocity: float, angle: float) -> float: 414.76 """ radians = angle_to_radians(2 * angle) - return round((init_velocity ** 2) * sin(radians) / g, 2) + return round(init_velocity ** 2 * sin(radians) / g, 2) def max_height(init_velocity: float, angle: float) -> float: @@ -62,7 +61,7 @@ def max_height(init_velocity: float, angle: float) -> float: """ radians = angle_to_radians(angle) - return round(((init_velocity ** 2) * (sin(radians)) ** 2) / (2 * g), 2) + return round((init_velocity ** 2 * sin(radians) ** 2) / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: @@ -84,7 +83,7 @@ def total_time(init_velocity: float, angle: float) -> float: """ radians = angle_to_radians(angle) - return round((2 * init_velocity) * (sin(radians)) / g, 2) + return round(2 * init_velocity * sin(radians) / g, 2) def test_motion() -> None: From 4e2fcaf6fbbf41b77c3538c60dd44a908982b27c Mon Sep 17 00:00:00 2001 From: Username Date: Tue, 7 Sep 2021 15:15:08 -0400 Subject: [PATCH 17/45] Fixes #4710 added exceptions and tests --- physics/horizontal_projectile_motion.py | 79 +++++++++++++++++++------ 1 file changed, 60 insertions(+), 19 deletions(-) diff --git a/physics/horizontal_projectile_motion.py b/physics/horizontal_projectile_motion.py index 1fb02f42cc2a..9abb7ede4cfe 100644 --- a/physics/horizontal_projectile_motion.py +++ b/physics/horizontal_projectile_motion.py @@ -21,6 +21,28 @@ # Acceleration Constant on hearth (unit m/s^2) g = 9.80665 + +def check_args(init_velocity: float, angle: float) -> None: + """ + Check that the arguments are valid + """ + + # Ensure valid instance + if not isinstance(init_velocity, (int, float)): + raise TypeError("Invalid velocity. Should be a positive number.") + + if not isinstance(angle, (int, float)): + raise TypeError("Invalid angle. Range is 1-90 degrees.") + + # Ensure valid angle + if angle > 90 or angle < 1: + raise ValueError("Invalid angle. Range is 1-90 degrees.") + + # Ensure valid velocity + if init_velocity < 0: + raise ValueError("Invalid velocity. Should be a positive number.") + + def horizontal_distance(init_velocity: float, angle: float) -> float: """ Returns the horizontal distance that the object cover @@ -37,7 +59,16 @@ def horizontal_distance(init_velocity: float, angle: float) -> float: 91.77 >>> horizontal_distance(100, 78) 414.76 + >>> horizontal_distance(-1, 20) + Traceback (most recent call last): + ... + ValueError: Invalid velocity. Should be a positive number. + >>> horizontal_distance(30, -20) + Traceback (most recent call last): + ... + ValueError: Invalid angle. Range is 1-90 degrees. """ + check_args(init_velocity, angle) radians = angle_to_radians(2 * angle) return round(init_velocity ** 2 * sin(radians) / g, 2) @@ -58,10 +89,18 @@ def max_height(init_velocity: float, angle: float) -> float: 22.94 >>> max_height(100, 78) 487.82 + >>> max_height("a", 20) + Traceback (most recent call last): + ... + TypeError: Invalid velocity. Should be a positive number. + >>> horizontal_distance(30, "b") + Traceback (most recent call last): + ... + TypeError: Invalid angle. Range is 1-90 degrees. """ - + check_args(init_velocity, angle) radians = angle_to_radians(angle) - return round((init_velocity ** 2 * sin(radians) ** 2) / (2 * g), 2) + return round(init_velocity ** 2 * sin(radians) ** 2 / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: @@ -80,8 +119,16 @@ def total_time(init_velocity: float, angle: float) -> float: 4.33 >>> total_time(100, 78) 19.95 + >>> total_time(-10, 40) + Traceback (most recent call last): + ... + ValueError: Invalid velocity. Should be a positive number. + >>> total_time(30, "b") + Traceback (most recent call last): + ... + TypeError: Invalid angle. Range is 1-90 degrees. """ - + check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(2 * init_velocity * sin(radians) / g, 2) @@ -97,25 +144,19 @@ def test_motion() -> None: if __name__ == "__main__": + from doctest import testmod - # Get input from user - init_vel = float(input("Initial Velocity: ")) + testmod() # Get input from user - angle = float(input("angle: ")) + init_vel = float(input("Initial Velocity: ").strip()) - # Ensure valid angle - if angle > 90 or angle < 1: - print("Error: Invalid angle. Range is 1-90 degrees.") - - # Ensure valid velocity - elif init_vel < 0: - print("Error: Invalid velocity. Should be a positive number.") + # Get input from user + angle = float(input("angle: ").strip()) # Print results - else: - print() - print("Results: ") - print(f"Horizontal Distance: {str(horizontal_distance(init_vel, angle))} [m]") - print(f"Maximum Height: {str(max_height(init_vel, angle))} [m]") - print(f"Total Time: {str(total_time(init_vel, angle))} [s]") + print() + print("Results: ") + print(f"Horizontal Distance: {str(horizontal_distance(init_vel, angle))} [m]") + print(f"Maximum Height: {str(max_height(init_vel, angle))} [m]") + print(f"Total Time: {str(total_time(init_vel, angle))} [s]") From dcacc95b9d5c7fe70951b9655551e6708130a212 Mon Sep 17 00:00:00 2001 From: Username Date: Tue, 7 Sep 2021 15:18:18 -0400 Subject: [PATCH 18/45] Added float tests --- physics/horizontal_projectile_motion.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/physics/horizontal_projectile_motion.py b/physics/horizontal_projectile_motion.py index 9abb7ede4cfe..404164f1882c 100644 --- a/physics/horizontal_projectile_motion.py +++ b/physics/horizontal_projectile_motion.py @@ -59,6 +59,8 @@ def horizontal_distance(init_velocity: float, angle: float) -> float: 91.77 >>> horizontal_distance(100, 78) 414.76 + >>> horizontal_distance(4.5, 5.5) + 0.39 >>> horizontal_distance(-1, 20) Traceback (most recent call last): ... @@ -89,6 +91,8 @@ def max_height(init_velocity: float, angle: float) -> float: 22.94 >>> max_height(100, 78) 487.82 + >>> max_height(4.5, 5.5) + 0.01 >>> max_height("a", 20) Traceback (most recent call last): ... @@ -119,6 +123,8 @@ def total_time(init_velocity: float, angle: float) -> float: 4.33 >>> total_time(100, 78) 19.95 + >>> total_time(4.5, 5.5) + 0.09 >>> total_time(-10, 40) Traceback (most recent call last): ... From 3f2b238c34cd926b335d1f6f750e009f08e8f270 Mon Sep 17 00:00:00 2001 From: Username Date: Tue, 14 Sep 2021 15:30:42 -0400 Subject: [PATCH 19/45] Fixed type annotations --- ciphers/enigma_machine2.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ciphers/enigma_machine2.py b/ciphers/enigma_machine2.py index f4ce5a075f46..b2b2953f4bc1 100644 --- a/ciphers/enigma_machine2.py +++ b/ciphers/enigma_machine2.py @@ -14,9 +14,9 @@ Created by TrapinchO """ - -RotorPositionT = tuple[int, int, int] -RotorSelectionT = tuple[str, str, str] +from typing import Tuple, Dict +RotorPositionT = Tuple[int, int, int] +RotorSelectionT = Tuple[str, str, str] # used alphabet -------------------------- @@ -69,7 +69,7 @@ def _validator( rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str -) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: +) -> tuple[RotorPositionT, RotorSelectionT, Dict[str, str]]: """ Checks if the values can be used for the 'enigma' function @@ -110,7 +110,7 @@ def _validator( return rotpos, rotsel, pbdict -def _plugboard(pbstring: str) -> dict[str, str]: +def _plugboard(pbstring: str) -> Dict[str, str]: """ https://en.wikipedia.org/wiki/Enigma_machine#Plugboard From e3678fdeadd23f1bfca27015ab524efa184f6c79 Mon Sep 17 00:00:00 2001 From: Username Date: Tue, 14 Sep 2021 15:35:51 -0400 Subject: [PATCH 20/45] Fixed last annotation --- ciphers/enigma_machine2.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ciphers/enigma_machine2.py b/ciphers/enigma_machine2.py index b2b2953f4bc1..3ed94c59de60 100644 --- a/ciphers/enigma_machine2.py +++ b/ciphers/enigma_machine2.py @@ -69,7 +69,7 @@ def _validator( rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str -) -> tuple[RotorPositionT, RotorSelectionT, Dict[str, str]]: +) -> Tuple[RotorPositionT, RotorSelectionT, Dict[str, str]]: """ Checks if the values can be used for the 'enigma' function From c37bb9540834cb77e37822eb376a5896cda34778 Mon Sep 17 00:00:00 2001 From: Username Date: Tue, 14 Sep 2021 15:42:02 -0400 Subject: [PATCH 21/45] Fixed annotations --- ciphers/a1z26.py | 7 +++++-- ciphers/trafid_cipher.py | 11 +++++++---- ciphers/xor_cipher.py | 7 +++++-- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/ciphers/a1z26.py b/ciphers/a1z26.py index e6684fb1e6fc..8f038a4026d2 100644 --- a/ciphers/a1z26.py +++ b/ciphers/a1z26.py @@ -7,7 +7,10 @@ """ -def encode(plain: str) -> list[int]: +from typing import List + + +def encode(plain: str) -> List[int]: """ >>> encode("myname") [13, 25, 14, 1, 13, 5] @@ -15,7 +18,7 @@ def encode(plain: str) -> list[int]: return [ord(elem) - 96 for elem in plain] -def decode(encoded: list[int]) -> str: +def decode(encoded: List[int]) -> str: """ >>> decode([13, 25, 14, 1, 13, 5]) 'myname' diff --git a/ciphers/trafid_cipher.py b/ciphers/trafid_cipher.py index 1c8ea3024d33..f4bf45b3dab7 100644 --- a/ciphers/trafid_cipher.py +++ b/ciphers/trafid_cipher.py @@ -1,7 +1,10 @@ # https://en.wikipedia.org/wiki/Trifid_cipher -def __encryptPart(messagePart: str, character2Number: dict[str, str]) -> str: +from typing import Tuple, Dict + + +def __encryptPart(messagePart: str, character2Number: Dict[str, str]) -> str: one, two, three = "", "", "" tmp = [] @@ -17,8 +20,8 @@ def __encryptPart(messagePart: str, character2Number: dict[str, str]) -> str: def __decryptPart( - messagePart: str, character2Number: dict[str, str] -) -> tuple[str, str, str]: + messagePart: str, character2Number: Dict[str, str] +) -> Tuple[str, str, str]: tmp, thisPart = "", "" result = [] @@ -36,7 +39,7 @@ def __decryptPart( def __prepare( message: str, alphabet: str -) -> tuple[str, str, dict[str, str], dict[str, str]]: +) -> Tuple[str, str, Dict[str, str], Dict[str, str]]: # Validate message and alphabet, set to upper and remove spaces alphabet = alphabet.replace(" ", "").upper() message = message.replace(" ", "").upper() diff --git a/ciphers/xor_cipher.py b/ciphers/xor_cipher.py index 12d580e720bc..6bd22ea24169 100644 --- a/ciphers/xor_cipher.py +++ b/ciphers/xor_cipher.py @@ -18,6 +18,9 @@ """ +from typing import List + + class XORCipher: def __init__(self, key: int = 0): """ @@ -28,7 +31,7 @@ def __init__(self, key: int = 0): # private field self.__key = key - def encrypt(self, content: str, key: int) -> list[str]: + def encrypt(self, content: str, key: int) -> List[str]: """ input: 'content' of type string and 'key' of type int output: encrypted string 'content' as a list of chars @@ -53,7 +56,7 @@ def encrypt(self, content: str, key: int) -> list[str]: return ans - def decrypt(self, content: str, key: int) -> list[str]: + def decrypt(self, content: str, key: int) -> List[str]: """ input: 'content' of type list and 'key' of type int output: decrypted string 'content' as a list of chars From 5b0249ac0a0f9c36c3cfbab8423eb72925a73ffb Mon Sep 17 00:00:00 2001 From: Username Date: Tue, 14 Sep 2021 15:44:10 -0400 Subject: [PATCH 22/45] fixed format --- ciphers/enigma_machine2.py | 3 ++- ciphers/trafid_cipher.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/ciphers/enigma_machine2.py b/ciphers/enigma_machine2.py index 3ed94c59de60..771c4db0da5b 100644 --- a/ciphers/enigma_machine2.py +++ b/ciphers/enigma_machine2.py @@ -14,7 +14,8 @@ Created by TrapinchO """ -from typing import Tuple, Dict +from typing import Dict, Tuple + RotorPositionT = Tuple[int, int, int] RotorSelectionT = Tuple[str, str, str] diff --git a/ciphers/trafid_cipher.py b/ciphers/trafid_cipher.py index f4bf45b3dab7..b0800b0f2bff 100644 --- a/ciphers/trafid_cipher.py +++ b/ciphers/trafid_cipher.py @@ -1,7 +1,7 @@ # https://en.wikipedia.org/wiki/Trifid_cipher -from typing import Tuple, Dict +from typing import Dict, Tuple def __encryptPart(messagePart: str, character2Number: Dict[str, str]) -> str: From ec790c6a79f15f209b72a6c3b39f04c8a8b58e43 Mon Sep 17 00:00:00 2001 From: Username Date: Tue, 14 Sep 2021 16:27:18 -0400 Subject: [PATCH 23/45] Revert "fixed format" This reverts commit 5b0249ac0a0f9c36c3cfbab8423eb72925a73ffb. Undo changes @wq --- ciphers/enigma_machine2.py | 3 +-- ciphers/trafid_cipher.py | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/ciphers/enigma_machine2.py b/ciphers/enigma_machine2.py index 771c4db0da5b..3ed94c59de60 100644 --- a/ciphers/enigma_machine2.py +++ b/ciphers/enigma_machine2.py @@ -14,8 +14,7 @@ Created by TrapinchO """ -from typing import Dict, Tuple - +from typing import Tuple, Dict RotorPositionT = Tuple[int, int, int] RotorSelectionT = Tuple[str, str, str] diff --git a/ciphers/trafid_cipher.py b/ciphers/trafid_cipher.py index b0800b0f2bff..f4bf45b3dab7 100644 --- a/ciphers/trafid_cipher.py +++ b/ciphers/trafid_cipher.py @@ -1,7 +1,7 @@ # https://en.wikipedia.org/wiki/Trifid_cipher -from typing import Dict, Tuple +from typing import Tuple, Dict def __encryptPart(messagePart: str, character2Number: Dict[str, str]) -> str: From e865929eb7ce3b1a3bd5b69f9fe8acc404856f63 Mon Sep 17 00:00:00 2001 From: Username Date: Tue, 14 Sep 2021 16:28:18 -0400 Subject: [PATCH 24/45] Revert "Fixed annotations" This reverts commit c37bb9540834cb77e37822eb376a5896cda34778. --- ciphers/a1z26.py | 7 ++----- ciphers/trafid_cipher.py | 11 ++++------- ciphers/xor_cipher.py | 7 ++----- 3 files changed, 8 insertions(+), 17 deletions(-) diff --git a/ciphers/a1z26.py b/ciphers/a1z26.py index 8f038a4026d2..e6684fb1e6fc 100644 --- a/ciphers/a1z26.py +++ b/ciphers/a1z26.py @@ -7,10 +7,7 @@ """ -from typing import List - - -def encode(plain: str) -> List[int]: +def encode(plain: str) -> list[int]: """ >>> encode("myname") [13, 25, 14, 1, 13, 5] @@ -18,7 +15,7 @@ def encode(plain: str) -> List[int]: return [ord(elem) - 96 for elem in plain] -def decode(encoded: List[int]) -> str: +def decode(encoded: list[int]) -> str: """ >>> decode([13, 25, 14, 1, 13, 5]) 'myname' diff --git a/ciphers/trafid_cipher.py b/ciphers/trafid_cipher.py index f4bf45b3dab7..1c8ea3024d33 100644 --- a/ciphers/trafid_cipher.py +++ b/ciphers/trafid_cipher.py @@ -1,10 +1,7 @@ # https://en.wikipedia.org/wiki/Trifid_cipher -from typing import Tuple, Dict - - -def __encryptPart(messagePart: str, character2Number: Dict[str, str]) -> str: +def __encryptPart(messagePart: str, character2Number: dict[str, str]) -> str: one, two, three = "", "", "" tmp = [] @@ -20,8 +17,8 @@ def __encryptPart(messagePart: str, character2Number: Dict[str, str]) -> str: def __decryptPart( - messagePart: str, character2Number: Dict[str, str] -) -> Tuple[str, str, str]: + messagePart: str, character2Number: dict[str, str] +) -> tuple[str, str, str]: tmp, thisPart = "", "" result = [] @@ -39,7 +36,7 @@ def __decryptPart( def __prepare( message: str, alphabet: str -) -> Tuple[str, str, Dict[str, str], Dict[str, str]]: +) -> tuple[str, str, dict[str, str], dict[str, str]]: # Validate message and alphabet, set to upper and remove spaces alphabet = alphabet.replace(" ", "").upper() message = message.replace(" ", "").upper() diff --git a/ciphers/xor_cipher.py b/ciphers/xor_cipher.py index 6bd22ea24169..12d580e720bc 100644 --- a/ciphers/xor_cipher.py +++ b/ciphers/xor_cipher.py @@ -18,9 +18,6 @@ """ -from typing import List - - class XORCipher: def __init__(self, key: int = 0): """ @@ -31,7 +28,7 @@ def __init__(self, key: int = 0): # private field self.__key = key - def encrypt(self, content: str, key: int) -> List[str]: + def encrypt(self, content: str, key: int) -> list[str]: """ input: 'content' of type string and 'key' of type int output: encrypted string 'content' as a list of chars @@ -56,7 +53,7 @@ def encrypt(self, content: str, key: int) -> List[str]: return ans - def decrypt(self, content: str, key: int) -> List[str]: + def decrypt(self, content: str, key: int) -> list[str]: """ input: 'content' of type list and 'key' of type int output: decrypted string 'content' as a list of chars From 82b4e0d7bf29f8a8cc5ee58cf1e6bdd9845d90f3 Mon Sep 17 00:00:00 2001 From: Username Date: Tue, 14 Sep 2021 16:28:38 -0400 Subject: [PATCH 25/45] Revert "Fixed last annotation" This reverts commit e3678fdeadd23f1bfca27015ab524efa184f6c79. --- ciphers/enigma_machine2.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ciphers/enigma_machine2.py b/ciphers/enigma_machine2.py index 3ed94c59de60..b2b2953f4bc1 100644 --- a/ciphers/enigma_machine2.py +++ b/ciphers/enigma_machine2.py @@ -69,7 +69,7 @@ def _validator( rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str -) -> Tuple[RotorPositionT, RotorSelectionT, Dict[str, str]]: +) -> tuple[RotorPositionT, RotorSelectionT, Dict[str, str]]: """ Checks if the values can be used for the 'enigma' function From 63c7c6a736b5756b853496b765ea43e29697b371 Mon Sep 17 00:00:00 2001 From: Username Date: Tue, 14 Sep 2021 16:28:52 -0400 Subject: [PATCH 26/45] Revert "Fixed type annotations" This reverts commit 3f2b238c34cd926b335d1f6f750e009f08e8f270. --- ciphers/enigma_machine2.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ciphers/enigma_machine2.py b/ciphers/enigma_machine2.py index b2b2953f4bc1..f4ce5a075f46 100644 --- a/ciphers/enigma_machine2.py +++ b/ciphers/enigma_machine2.py @@ -14,9 +14,9 @@ Created by TrapinchO """ -from typing import Tuple, Dict -RotorPositionT = Tuple[int, int, int] -RotorSelectionT = Tuple[str, str, str] + +RotorPositionT = tuple[int, int, int] +RotorSelectionT = tuple[str, str, str] # used alphabet -------------------------- @@ -69,7 +69,7 @@ def _validator( rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str -) -> tuple[RotorPositionT, RotorSelectionT, Dict[str, str]]: +) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: """ Checks if the values can be used for the 'enigma' function @@ -110,7 +110,7 @@ def _validator( return rotpos, rotsel, pbdict -def _plugboard(pbstring: str) -> Dict[str, str]: +def _plugboard(pbstring: str) -> dict[str, str]: """ https://en.wikipedia.org/wiki/Enigma_machine#Plugboard From 805050e8975225a7f4df358e821c051e47f10162 Mon Sep 17 00:00:00 2001 From: Username Date: Mon, 4 Apr 2022 08:56:01 -0400 Subject: [PATCH 27/45] Revert to 4e2fcaf6fb --- physics/horizontal_projectile_motion.py | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/physics/horizontal_projectile_motion.py b/physics/horizontal_projectile_motion.py index 404164f1882c..2ec32ff1791f 100644 --- a/physics/horizontal_projectile_motion.py +++ b/physics/horizontal_projectile_motion.py @@ -10,7 +10,6 @@ * * * * GROUND GROUND - For more info: https://en.wikipedia.org/wiki/Projectile_motion """ @@ -46,21 +45,16 @@ def check_args(init_velocity: float, angle: float) -> None: def horizontal_distance(init_velocity: float, angle: float) -> float: """ Returns the horizontal distance that the object cover - Formula: v_0^2 * sin(2 * alpha) --------------------- g - v_0 - initial velocity alpha - angle - >>> horizontal_distance(30, 45) 91.77 >>> horizontal_distance(100, 78) 414.76 - >>> horizontal_distance(4.5, 5.5) - 0.39 >>> horizontal_distance(-1, 20) Traceback (most recent call last): ... @@ -78,21 +72,16 @@ def horizontal_distance(init_velocity: float, angle: float) -> float: def max_height(init_velocity: float, angle: float) -> float: """ Returns the maximum height that the object reach - Formula: v_0^2 * sin^2(alpha) -------------------- 2g - v_0 - initial velocity alpha - angle - >>> max_height(30, 45) 22.94 >>> max_height(100, 78) 487.82 - >>> max_height(4.5, 5.5) - 0.01 >>> max_height("a", 20) Traceback (most recent call last): ... @@ -110,21 +99,16 @@ def max_height(init_velocity: float, angle: float) -> float: def total_time(init_velocity: float, angle: float) -> float: """ Returns total time of the motion - Formula: 2 * v_0 * sin(alpha) -------------------- g - v_0 - initial velocity alpha - angle - >>> total_time(30, 45) 4.33 >>> total_time(100, 78) 19.95 - >>> total_time(4.5, 5.5) - 0.09 >>> total_time(-10, 40) Traceback (most recent call last): ... @@ -165,4 +149,4 @@ def test_motion() -> None: print("Results: ") print(f"Horizontal Distance: {str(horizontal_distance(init_vel, angle))} [m]") print(f"Maximum Height: {str(max_height(init_vel, angle))} [m]") - print(f"Total Time: {str(total_time(init_vel, angle))} [s]") + print(f"Total Time: {str(total_time(init_vel, angle))} [s]") \ No newline at end of file From 5f3486c9d13dac2b0ebc2cdd62f41135294d2da3 Mon Sep 17 00:00:00 2001 From: Username Date: Mon, 4 Apr 2022 09:09:38 -0400 Subject: [PATCH 28/45] Fixing errors found during pre-commit --- physics/horizontal_projectile_motion.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/physics/horizontal_projectile_motion.py b/physics/horizontal_projectile_motion.py index 2ec32ff1791f..0f27b0617105 100644 --- a/physics/horizontal_projectile_motion.py +++ b/physics/horizontal_projectile_motion.py @@ -66,7 +66,7 @@ def horizontal_distance(init_velocity: float, angle: float) -> float: """ check_args(init_velocity, angle) radians = angle_to_radians(2 * angle) - return round(init_velocity ** 2 * sin(radians) / g, 2) + return round(init_velocity**2 * sin(radians) / g, 2) def max_height(init_velocity: float, angle: float) -> float: @@ -93,7 +93,7 @@ def max_height(init_velocity: float, angle: float) -> float: """ check_args(init_velocity, angle) radians = angle_to_radians(angle) - return round(init_velocity ** 2 * sin(radians) ** 2 / (2 * g), 2) + return round(init_velocity**2 * sin(radians) ** 2 / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: @@ -149,4 +149,4 @@ def test_motion() -> None: print("Results: ") print(f"Horizontal Distance: {str(horizontal_distance(init_vel, angle))} [m]") print(f"Maximum Height: {str(max_height(init_vel, angle))} [m]") - print(f"Total Time: {str(total_time(init_vel, angle))} [s]") \ No newline at end of file + print(f"Total Time: {str(total_time(init_vel, angle))} [s]") From 99f00b5b3f61a4bbe55368a47986c4fde50a27a5 Mon Sep 17 00:00:00 2001 From: Username Date: Tue, 5 Apr 2022 16:35:35 -0400 Subject: [PATCH 29/45] Added gauss law --- physics/gauss_law.py | 89 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 physics/gauss_law.py diff --git a/physics/gauss_law.py b/physics/gauss_law.py new file mode 100644 index 000000000000..bb488d312d67 --- /dev/null +++ b/physics/gauss_law.py @@ -0,0 +1,89 @@ +# https://byjus.com/jee/gauss-law/ + +from __future__ import annotations + +# Permittivity of free space -> units = C^2 / (N * m^2) +ε0 = 8.8541878128E-12 + + +def gauss_law(electric_field: float = 0, area: float = 0, charge: float = 0, res : str = "Flux") -> float: + + """ + Gauss law states that the flux through a closed surface (e.g. sphere) + is equal to the electric charge within this shape divided by an electric constant (ε0). + Formula: + q + E * S = ---- + ε0 + + Where E is an Electric Field flowing thorugh the surface S, and q is the total charge + within the closed surface. + + References + ---------- + https://byjus.com/jee/gauss-law/ + https://courses.lumenlearning.com/boundless-physics/chapter/electric-flux-and-gausss-law/ + + + Parameters + ---------- + electric_field : float units N / C + + area : float units m^2 + + charge : float with units in Coulombs + + res : str with options: Field, Flux, Charge. + + Returns + ------- + Returned value depends on the value of res: + + Flux --> flow of electric field through surface (units: N * m^2 * C^−1). + + Field --> Electric Field at a point in which the area was calculated. + The area should be of an enclosed shape and could be virtual (no need for a physical object). + The units of the electric field are: N / C + + Charge --> The total charge within an enclosed surface having flux that is equal to electric_field * area. + Units: C (Columb) + + >>> gauss_law(electric_field = 10, area = 3, res = "Charge") + 2.6562563438400003e-10 + + >>> gauss_law(charge = 18e-9, res = "Flux") + 2032.9363212714343 + + >>> gauss_law(area = 10, charge = 18e-9, res = "Field") + 203.2936321271434 + + >>> gauss_law() + Traceback (most recent call last): + ... + ValueError: One or more arguments are missing! + + >>> gauss_law(area = 10, res= "Field") + Traceback (most recent call last): + ... + ValueError: One or more arguments are missing! + """ + if res == "Flux": + if abs(charge) > 0: + return charge / ε0 + elif electric_field > 0 and area > 0: + return electric_field * area + elif res == "Field": + if abs(charge) > 0 and area > 0: + return charge / (ε0 * area) + elif res == "Charge": + if electric_field > 0 and area > 0: + return electric_field * area * ε0 + + raise ValueError("One or more arguments are missing!") + + + +if __name__ == "__main__": + import doctest + + doctest.testmod() From c75582f56e0e660f3c1e5a2821cc6089b177ad5e Mon Sep 17 00:00:00 2001 From: Username Date: Wed, 13 Apr 2022 18:31:38 -0400 Subject: [PATCH 30/45] Implemented Lorenz tranformation with four vector --- physics/__init__.py | 0 physics/gauss_law.py | 89 -------------- physics/lorenz_transformation_four_vector.py | 116 +++++++++++++++++++ 3 files changed, 116 insertions(+), 89 deletions(-) create mode 100644 physics/__init__.py delete mode 100644 physics/gauss_law.py create mode 100644 physics/lorenz_transformation_four_vector.py diff --git a/physics/__init__.py b/physics/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/physics/gauss_law.py b/physics/gauss_law.py deleted file mode 100644 index bb488d312d67..000000000000 --- a/physics/gauss_law.py +++ /dev/null @@ -1,89 +0,0 @@ -# https://byjus.com/jee/gauss-law/ - -from __future__ import annotations - -# Permittivity of free space -> units = C^2 / (N * m^2) -ε0 = 8.8541878128E-12 - - -def gauss_law(electric_field: float = 0, area: float = 0, charge: float = 0, res : str = "Flux") -> float: - - """ - Gauss law states that the flux through a closed surface (e.g. sphere) - is equal to the electric charge within this shape divided by an electric constant (ε0). - Formula: - q - E * S = ---- - ε0 - - Where E is an Electric Field flowing thorugh the surface S, and q is the total charge - within the closed surface. - - References - ---------- - https://byjus.com/jee/gauss-law/ - https://courses.lumenlearning.com/boundless-physics/chapter/electric-flux-and-gausss-law/ - - - Parameters - ---------- - electric_field : float units N / C - - area : float units m^2 - - charge : float with units in Coulombs - - res : str with options: Field, Flux, Charge. - - Returns - ------- - Returned value depends on the value of res: - - Flux --> flow of electric field through surface (units: N * m^2 * C^−1). - - Field --> Electric Field at a point in which the area was calculated. - The area should be of an enclosed shape and could be virtual (no need for a physical object). - The units of the electric field are: N / C - - Charge --> The total charge within an enclosed surface having flux that is equal to electric_field * area. - Units: C (Columb) - - >>> gauss_law(electric_field = 10, area = 3, res = "Charge") - 2.6562563438400003e-10 - - >>> gauss_law(charge = 18e-9, res = "Flux") - 2032.9363212714343 - - >>> gauss_law(area = 10, charge = 18e-9, res = "Field") - 203.2936321271434 - - >>> gauss_law() - Traceback (most recent call last): - ... - ValueError: One or more arguments are missing! - - >>> gauss_law(area = 10, res= "Field") - Traceback (most recent call last): - ... - ValueError: One or more arguments are missing! - """ - if res == "Flux": - if abs(charge) > 0: - return charge / ε0 - elif electric_field > 0 and area > 0: - return electric_field * area - elif res == "Field": - if abs(charge) > 0 and area > 0: - return charge / (ε0 * area) - elif res == "Charge": - if electric_field > 0 and area > 0: - return electric_field * area * ε0 - - raise ValueError("One or more arguments are missing!") - - - -if __name__ == "__main__": - import doctest - - doctest.testmod() diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py new file mode 100644 index 000000000000..57a4b4e24e6b --- /dev/null +++ b/physics/lorenz_transformation_four_vector.py @@ -0,0 +1,116 @@ +""" +Lorenz transformation describes the transition from a reference frame P +to another reference frame P', each of which is moving in a direction with +respect to the other. The Lorenz transformation implemented in this code +is the relativistic version using a four vector described by Minkowsky Space: +x0 = ct, x1 = x, x2 = y, and x3 = z + +NOTE: Please note that x0 is c (speed of light) times t (time). + +So, the Lorenz transformation using a four vector is defined as: + +|ct'| | γ -γβ 0 0| |ct| +|x' | = |-γβ γ 0 0| *|x | +|y' | | 0 0 1 0| |y | +|z' | | 0 0 0 1| |z | + +Where: + 1 +γ = --------------- + ----------- + / v^2 | + /(1 - --- + -/ c^2 + + v +β = ----- + c +""" +from __future__ import annotations +from math import sqrt +import numpy as np # type: ignore +from sympy import symbols # type: ignore + + +# Coefficient +# Speed of light (m/s) +c = 299792458 + +# Vehicle's speed divided by speed of light (no units) +beta_u = lambda u: u / c + +gamma_u = lambda u: 1 / (sqrt(1 - beta_u(u) ** 2)) + +transformation_matrix = lambda u: np.array([ + [gamma_u(u), -gamma_u(u) * beta_u(u), 0, 0], + [-gamma_u(u) * beta_u(u), gamma_u(u), 0, 0], + [0,0,1,0], + [0,0,0,1]]) + +ct,x,y,z = symbols('ct x y z') +ct_p, x_p, y_p, z_p = symbols('ct\' x\' y\' z\'') + +def transform(v: float, event: np.array = np.zeros(4)): + """ + >>> transform(29979245,np.array([1,2,3,4])) + array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00]) + + >>> transform(29979245) + array([1.00503781498831*ct - 0.100503778816875*x, + -0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z], + dtype=object) + + >>> transform(19879210.2) + array([1.0022057787097*ct - 0.066456172618675*x, + -0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z], + dtype=object) + + >>> transform(299792459, np.array([1,1,1,1])) + Traceback (most recent call last): + ... + ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]! + + >>> transform(-1, np.array([1,1,1,1])) + Traceback (most recent call last): + ... + ValueError: Speed must be a positive integer! + """ + if v >= c: + raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!") + + # Usually the speed u should be much higher than 1 (c order of magnitude) + elif v < 1: + raise ValueError("Speed must be a positive integer!") + # Ensure event is not a vector of zeros + if np.all(event): + + # x0 is ct (speed of ligt * time) + event[0] = event[0] * c + else: + + # Symbolic four vector + event = np.array([ct, x, y, z]) + + return transformation_matrix(v).dot(event) + + + + +if __name__ == "__main__": + import doctest + doctest.testmod() + + # Example of symbolic vector: + four_vector = transform(29979245) + print("Example of four vector: ") + print(f"ct\' = {four_vector[0]}") + print(f"x\' = {four_vector[1]}") + print(f"y\' = {four_vector[2]}") + print(f"z\' = {four_vector[3]}") + + # Substitute symbols with numerical values: + values = np.array([1,1,1,1]) + sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]} + numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0,4)] + + print(f"\n{numerical_vector}") \ No newline at end of file From a462736fb2ec3fec34e877f4758c0e99d395e2b4 Mon Sep 17 00:00:00 2001 From: Username Date: Wed, 13 Apr 2022 18:37:02 -0400 Subject: [PATCH 31/45] pre-commit fixes --- physics/lorenz_transformation_four_vector.py | 114 ++++++++++--------- 1 file changed, 59 insertions(+), 55 deletions(-) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index 57a4b4e24e6b..6623a2f2c25e 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -19,7 +19,7 @@ γ = --------------- ----------- / v^2 | - /(1 - --- + /(1 - --- -/ c^2 v @@ -27,10 +27,11 @@ c """ from __future__ import annotations + from math import sqrt -import numpy as np # type: ignore -from sympy import symbols # type: ignore +import numpy as np # type: ignore +from sympy import symbols # type: ignore # Coefficient # Speed of light (m/s) @@ -41,22 +42,26 @@ gamma_u = lambda u: 1 / (sqrt(1 - beta_u(u) ** 2)) -transformation_matrix = lambda u: np.array([ - [gamma_u(u), -gamma_u(u) * beta_u(u), 0, 0], - [-gamma_u(u) * beta_u(u), gamma_u(u), 0, 0], - [0,0,1,0], - [0,0,0,1]]) +transformation_matrix = lambda u: np.array( + [ + [gamma_u(u), -gamma_u(u) * beta_u(u), 0, 0], + [-gamma_u(u) * beta_u(u), gamma_u(u), 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1], + ] +) + +ct, x, y, z = symbols("ct x y z") +ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'") -ct,x,y,z = symbols('ct x y z') -ct_p, x_p, y_p, z_p = symbols('ct\' x\' y\' z\'') def transform(v: float, event: np.array = np.zeros(4)): - """ - >>> transform(29979245,np.array([1,2,3,4])) - array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00]) + """ + >>> transform(29979245,np.array([1,2,3,4])) + array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00]) - >>> transform(29979245) - array([1.00503781498831*ct - 0.100503778816875*x, + >>> transform(29979245) + array([1.00503781498831*ct - 0.100503778816875*x, -0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z], dtype=object) @@ -65,52 +70,51 @@ def transform(v: float, event: np.array = np.zeros(4)): -0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z], dtype=object) - >>> transform(299792459, np.array([1,1,1,1])) - Traceback (most recent call last): - ... - ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]! + >>> transform(299792459, np.array([1,1,1,1])) + Traceback (most recent call last): + ... + ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]! + + >>> transform(-1, np.array([1,1,1,1])) + Traceback (most recent call last): + ... + ValueError: Speed must be a positive integer! + """ + if v >= c: + raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!") - >>> transform(-1, np.array([1,1,1,1])) - Traceback (most recent call last): - ... - ValueError: Speed must be a positive integer! - """ - if v >= c: - raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!") + # Usually the speed u should be much higher than 1 (c order of magnitude) + elif v < 1: + raise ValueError("Speed must be a positive integer!") + # Ensure event is not a vector of zeros + if np.all(event): - # Usually the speed u should be much higher than 1 (c order of magnitude) - elif v < 1: - raise ValueError("Speed must be a positive integer!") - # Ensure event is not a vector of zeros - if np.all(event): + # x0 is ct (speed of ligt * time) + event[0] = event[0] * c + else: - # x0 is ct (speed of ligt * time) - event[0] = event[0] * c - else: + # Symbolic four vector + event = np.array([ct, x, y, z]) - # Symbolic four vector - event = np.array([ct, x, y, z]) + return transformation_matrix(v).dot(event) - return transformation_matrix(v).dot(event) +if __name__ == "__main__": + import doctest + doctest.testmod() + # Example of symbolic vector: + four_vector = transform(29979245) + print("Example of four vector: ") + print(f"ct' = {four_vector[0]}") + print(f"x' = {four_vector[1]}") + print(f"y' = {four_vector[2]}") + print(f"z' = {four_vector[3]}") -if __name__ == "__main__": - import doctest - doctest.testmod() - - # Example of symbolic vector: - four_vector = transform(29979245) - print("Example of four vector: ") - print(f"ct\' = {four_vector[0]}") - print(f"x\' = {four_vector[1]}") - print(f"y\' = {four_vector[2]}") - print(f"z\' = {four_vector[3]}") - - # Substitute symbols with numerical values: - values = np.array([1,1,1,1]) - sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]} - numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0,4)] - - print(f"\n{numerical_vector}") \ No newline at end of file + # Substitute symbols with numerical values: + values = np.array([1, 1, 1, 1]) + sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]} + numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0, 4)] + + print(f"\n{numerical_vector}") From 4eab40b5efa9b51cb08557d7bcbd9157c12fb14a Mon Sep 17 00:00:00 2001 From: Username Date: Wed, 13 Apr 2022 18:44:04 -0400 Subject: [PATCH 32/45] flake8 fixes --- physics/lorenz_transformation_four_vector.py | 38 +++++++++++--------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index 6623a2f2c25e..0f28410081dc 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -17,14 +17,14 @@ Where: 1 γ = --------------- - ----------- - / v^2 | + ----------- + / v^2 | /(1 - --- - -/ c^2 + -/ c^2 - v + v β = ----- - c + c """ from __future__ import annotations @@ -38,18 +38,24 @@ c = 299792458 # Vehicle's speed divided by speed of light (no units) -beta_u = lambda u: u / c +def beta(u: float) -> float: + return u / c -gamma_u = lambda u: 1 / (sqrt(1 - beta_u(u) ** 2)) -transformation_matrix = lambda u: np.array( - [ - [gamma_u(u), -gamma_u(u) * beta_u(u), 0, 0], - [-gamma_u(u) * beta_u(u), gamma_u(u), 0, 0], - [0, 0, 1, 0], - [0, 0, 0, 1], - ] -) +def gamma(u: float) -> float: + return 1 / (sqrt(1 - beta(u) ** 2)) + + +def transformation_matrix(u: float) -> np.array: + return np.array( + [ + [gamma(u), -gamma(u) * beta(u), 0, 0], + [-gamma(u) * beta(u), gamma(u), 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1], + ] + ) + ct, x, y, z = symbols("ct x y z") ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'") @@ -117,4 +123,4 @@ def transform(v: float, event: np.array = np.zeros(4)): sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]} numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0, 4)] - print(f"\n{numerical_vector}") + print(f"\n{numerical_vector}") \ No newline at end of file From 9d0e75cbd446fdeef7726dba3686a9ed21d8672f Mon Sep 17 00:00:00 2001 From: Username Date: Wed, 13 Apr 2022 18:45:57 -0400 Subject: [PATCH 33/45] More flake8 fixes --- physics/lorenz_transformation_four_vector.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index 0f28410081dc..49f6b7cf72d5 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -123,4 +123,4 @@ def transform(v: float, event: np.array = np.zeros(4)): sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]} numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0, 4)] - print(f"\n{numerical_vector}") \ No newline at end of file + print(f"\n{numerical_vector}") From 7cfaf9ed624d9e7adc5b24269ee888c5ba6290c5 Mon Sep 17 00:00:00 2001 From: Username Date: Wed, 13 Apr 2022 18:48:03 -0400 Subject: [PATCH 34/45] Added blank space for flake8 --- physics/lorenz_transformation_four_vector.py | 1 + 1 file changed, 1 insertion(+) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index 49f6b7cf72d5..73311e432284 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -37,6 +37,7 @@ # Speed of light (m/s) c = 299792458 + # Vehicle's speed divided by speed of light (no units) def beta(u: float) -> float: return u / c From 83cbeca849807236d39a858bd1c1bb5a68f9caf8 Mon Sep 17 00:00:00 2001 From: Username Date: Wed, 13 Apr 2022 18:54:38 -0400 Subject: [PATCH 35/45] Added reference --- physics/lorenz_transformation_four_vector.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index 73311e432284..16b091d8fb0c 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -25,6 +25,8 @@ v β = ----- c + +Reference: http://hyperphysics.phy-astr.gsu.edu/hbase/Relativ/vec4.html """ from __future__ import annotations From a080632df7ced1aca1d98b5074ec377b0c6f72f7 Mon Sep 17 00:00:00 2001 From: Username Date: Wed, 13 Apr 2022 18:56:03 -0400 Subject: [PATCH 36/45] Trailing whitespace fix --- physics/lorenz_transformation_four_vector.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index 16b091d8fb0c..0e57c7993b8d 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -26,7 +26,7 @@ β = ----- c -Reference: http://hyperphysics.phy-astr.gsu.edu/hbase/Relativ/vec4.html +Reference: http://hyperphysics.phy-astr.gsu.edu/hbase/Relativ/vec4.html """ from __future__ import annotations From 36f0cd70ae3ebb781f2b0d0f07a12991e3d68716 Mon Sep 17 00:00:00 2001 From: Username Date: Thu, 14 Apr 2022 16:49:11 -0400 Subject: [PATCH 37/45] Replaced argument u with velocity (descriptive name fix) --- physics/lorenz_transformation_four_vector.py | 22 ++++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index 0e57c7993b8d..8cda7677f768 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -41,19 +41,19 @@ # Vehicle's speed divided by speed of light (no units) -def beta(u: float) -> float: - return u / c +def beta(velocity: float) -> float: + return velocity / c -def gamma(u: float) -> float: - return 1 / (sqrt(1 - beta(u) ** 2)) +def gamma(velocity: float) -> float: + return 1 / (sqrt(1 - beta(velocity) ** 2)) -def transformation_matrix(u: float) -> np.array: +def transformation_matrix(velocity: float) -> np.array: return np.array( [ - [gamma(u), -gamma(u) * beta(u), 0, 0], - [-gamma(u) * beta(u), gamma(u), 0, 0], + [gamma(velocity), -gamma(velocity) * beta(velocity), 0, 0], + [-gamma(velocity) * beta(velocity), gamma(velocity), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] @@ -64,7 +64,7 @@ def transformation_matrix(u: float) -> np.array: ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'") -def transform(v: float, event: np.array = np.zeros(4)): +def transform(velocity: float, event: np.array = np.zeros(4)) -> np.array: """ >>> transform(29979245,np.array([1,2,3,4])) array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00]) @@ -89,11 +89,11 @@ def transform(v: float, event: np.array = np.zeros(4)): ... ValueError: Speed must be a positive integer! """ - if v >= c: + if velocity >= c: raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!") # Usually the speed u should be much higher than 1 (c order of magnitude) - elif v < 1: + elif velocity < 1: raise ValueError("Speed must be a positive integer!") # Ensure event is not a vector of zeros if np.all(event): @@ -105,7 +105,7 @@ def transform(v: float, event: np.array = np.zeros(4)): # Symbolic four vector event = np.array([ct, x, y, z]) - return transformation_matrix(v).dot(event) + return transformation_matrix(velocity).dot(event) if __name__ == "__main__": From b31721da3fa163a3052b71bb3171c06f7b1357f1 Mon Sep 17 00:00:00 2001 From: Username Date: Thu, 14 Apr 2022 18:50:03 -0400 Subject: [PATCH 38/45] Added tests for functions + moved velocity check to beta function --- physics/lorenz_transformation_four_vector.py | 103 ++++++++++++++----- 1 file changed, 79 insertions(+), 24 deletions(-) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index 8cda7677f768..228fc526e303 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -39,17 +39,82 @@ # Speed of light (m/s) c = 299792458 +# Symbols +ct, x, y, z = symbols("ct x y z") +ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'") + # Vehicle's speed divided by speed of light (no units) def beta(velocity: float) -> float: + """ + >>> beta(c) + 1.0 + + >>> beta(199792458) + 0.666435904801848 + + >> beta(1e5) + 4.5031152851750526e-07 + + >>> beta(0.2) + Traceback (most recent call last): + ... + ValueError: Speed must be greater than 1! + """ + if velocity > c: + raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!") + + # Usually the speed u should be much higher than 1 (c order of magnitude) + elif velocity < 1: + raise ValueError("Speed must be greater than 1!") return velocity / c def gamma(velocity: float) -> float: + """ + >> gamma(4) + 1.0000000000000002 + + >> gamma(1e5) + 1.0000000556325075 + + >> gamma(3e7) + 1.005044845777813 + + >> gamma(2.8e8) + 2.7985595722318277 + + >> gamma(299792451) + 4627.49902669495 + """ return 1 / (sqrt(1 - beta(velocity) ** 2)) def transformation_matrix(velocity: float) -> np.array: + """ + >> transformation_matrix(29979245) + [[ 1.00503781 -0.10050378 0. 0. ] + [-0.10050378 1.00503781 0. 0. ] + [ 0. 0. 1. 0. ] + [ 0. 0. 0. 1. ]] + + >> transformation_matrix(19979245.2) + [[ 1.00222811 -0.06679208 0. 0. ] + [-0.06679208 1.00222811 0. 0. ] + [ 0. 0. 1. 0. ] + [ 0. 0. 0. 1. ]] + + >> transformation_matrix(1) + [[ 1.00000000e+00 -3.33564095e-09 0.00000000e+00 0.00000000e+00] + [-3.33564095e-09 1.00000000e+00 0.00000000e+00 0.00000000e+00] + [ 0.00000000e+00 0.00000000e+00 1.00000000e+00 0.00000000e+00] + [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 1.00000000e+00]] + + >> transformation_matrix(0) + Traceback (most recent call last): + ... + ValueError: Speed must be greater than 1! + """ return np.array( [ [gamma(velocity), -gamma(velocity) * beta(velocity), 0, 0], @@ -60,41 +125,31 @@ def transformation_matrix(velocity: float) -> np.array: ) -ct, x, y, z = symbols("ct x y z") -ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'") - - def transform(velocity: float, event: np.array = np.zeros(4)) -> np.array: """ - >>> transform(29979245,np.array([1,2,3,4])) - array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00]) + >>> transform(29979245,np.array([1,2,3,4])) + array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00]) - >>> transform(29979245) - array([1.00503781498831*ct - 0.100503778816875*x, - -0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z], - dtype=object) + >>> transform(29979245) + array([1.00503781498831*ct - 0.100503778816875*x, + -0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z], + dtype=object) >>> transform(19879210.2) array([1.0022057787097*ct - 0.066456172618675*x, -0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z], dtype=object) - >>> transform(299792459, np.array([1,1,1,1])) - Traceback (most recent call last): - ... - ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]! + >>> transform(299792459, np.array([1,1,1,1])) + Traceback (most recent call last): + ... + ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]! - >>> transform(-1, np.array([1,1,1,1])) - Traceback (most recent call last): - ... - ValueError: Speed must be a positive integer! + >>> transform(-1, np.array([1,1,1,1])) + Traceback (most recent call last): + ... + ValueError: Speed must be greater than 1! """ - if velocity >= c: - raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!") - - # Usually the speed u should be much higher than 1 (c order of magnitude) - elif velocity < 1: - raise ValueError("Speed must be a positive integer!") # Ensure event is not a vector of zeros if np.all(event): From b1bbc832b7b575cdfe9367f3b54cfc983a2f1ac3 Mon Sep 17 00:00:00 2001 From: Username Date: Thu, 14 Apr 2022 18:53:54 -0400 Subject: [PATCH 39/45] Modified condition to 'not symbolic' in the transform function --- physics/lorenz_transformation_four_vector.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index 228fc526e303..a4c5b00568ca 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -125,9 +125,9 @@ def transformation_matrix(velocity: float) -> np.array: ) -def transform(velocity: float, event: np.array = np.zeros(4)) -> np.array: +def transform(velocity: float, event: np.array = np.zeros(4), symbolic = True) -> np.array: """ - >>> transform(29979245,np.array([1,2,3,4])) + >>> transform(29979245,np.array([1,2,3,4]), False) array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00]) >>> transform(29979245) @@ -151,7 +151,7 @@ def transform(velocity: float, event: np.array = np.zeros(4)) -> np.array: ValueError: Speed must be greater than 1! """ # Ensure event is not a vector of zeros - if np.all(event): + if not symbolic: # x0 is ct (speed of ligt * time) event[0] = event[0] * c From ee3601fac5af0a4496de049d4fd197e8c9909760 Mon Sep 17 00:00:00 2001 From: Username Date: Thu, 14 Apr 2022 18:58:47 -0400 Subject: [PATCH 40/45] trainling whitespace fix --- physics/lorenz_transformation_four_vector.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index a4c5b00568ca..769350ea060d 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -39,7 +39,7 @@ # Speed of light (m/s) c = 299792458 -# Symbols +# Symbols ct, x, y, z = symbols("ct x y z") ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'") @@ -125,7 +125,9 @@ def transformation_matrix(velocity: float) -> np.array: ) -def transform(velocity: float, event: np.array = np.zeros(4), symbolic = True) -> np.array: +def transform( + velocity: float, event: np.array = np.zeros(4), symbolic=True +) -> np.array: """ >>> transform(29979245,np.array([1,2,3,4]), False) array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00]) From 4e337f6290ed3f9be48534ac4fb54e678fa25888 Mon Sep 17 00:00:00 2001 From: Username Date: Fri, 15 Apr 2022 16:10:06 -0400 Subject: [PATCH 41/45] Added type hint for 'smybolic' argument in transform function --- physics/lorenz_transformation_four_vector.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index 769350ea060d..47fecb0e3f8f 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -126,7 +126,7 @@ def transformation_matrix(velocity: float) -> np.array: def transform( - velocity: float, event: np.array = np.zeros(4), symbolic=True + velocity: float, event: np.array = np.zeros(4), symbolic: bool = True ) -> np.array: """ >>> transform(29979245,np.array([1,2,3,4]), False) From 798b91f7641b9812041d0269ce2a162bb26f8069 Mon Sep 17 00:00:00 2001 From: Username Date: Fri, 15 Apr 2022 16:12:16 -0400 Subject: [PATCH 42/45] Changed reference to avoid pre-commit fails because of spelling issue related to the URL --- physics/lorenz_transformation_four_vector.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index 47fecb0e3f8f..45103c8ab639 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -26,7 +26,7 @@ β = ----- c -Reference: http://hyperphysics.phy-astr.gsu.edu/hbase/Relativ/vec4.html +Reference: https://en.wikipedia.org/wiki/Lorentz_transformation """ from __future__ import annotations From 982d66bcd8a51a571a48feeb03d7a6cd4090bccd Mon Sep 17 00:00:00 2001 From: Username Date: Fri, 15 Apr 2022 16:23:19 -0400 Subject: [PATCH 43/45] Added tests for gamma and transformation_matrix functions --- physics/lorenz_transformation_four_vector.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index 45103c8ab639..e84b50aff0d7 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -86,6 +86,16 @@ def gamma(velocity: float) -> float: >> gamma(299792451) 4627.49902669495 + + >>> gamma(0.3) + Traceback (most recent call last): + ... + ValueError: Speed must be greater than 1! + + >>> gamma(2*c) + Traceback (most recent call last): + ... + ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]! """ return 1 / (sqrt(1 - beta(velocity) ** 2)) @@ -114,6 +124,11 @@ def transformation_matrix(velocity: float) -> np.array: Traceback (most recent call last): ... ValueError: Speed must be greater than 1! + + >> transformation_matrix(c * 1.5) + Traceback (most recent call last): + ... + ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]! """ return np.array( [ From ec4dbfb28ed93436b2b764908bbd8c3b133938a9 Mon Sep 17 00:00:00 2001 From: Username Date: Sun, 17 Apr 2022 17:32:16 -0400 Subject: [PATCH 44/45] Fixed transformation_matrix tests --- physics/lorenz_transformation_four_vector.py | 44 +++++++++++--------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index e84b50aff0d7..12aef4845b88 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -102,30 +102,34 @@ def gamma(velocity: float) -> float: def transformation_matrix(velocity: float) -> np.array: """ - >> transformation_matrix(29979245) - [[ 1.00503781 -0.10050378 0. 0. ] - [-0.10050378 1.00503781 0. 0. ] - [ 0. 0. 1. 0. ] - [ 0. 0. 0. 1. ]] - - >> transformation_matrix(19979245.2) - [[ 1.00222811 -0.06679208 0. 0. ] - [-0.06679208 1.00222811 0. 0. ] - [ 0. 0. 1. 0. ] - [ 0. 0. 0. 1. ]] - - >> transformation_matrix(1) - [[ 1.00000000e+00 -3.33564095e-09 0.00000000e+00 0.00000000e+00] - [-3.33564095e-09 1.00000000e+00 0.00000000e+00 0.00000000e+00] - [ 0.00000000e+00 0.00000000e+00 1.00000000e+00 0.00000000e+00] - [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 1.00000000e+00]] - - >> transformation_matrix(0) + >>> transformation_matrix(29979245) + array([[ 1.00503781, -0.10050378, 0. , 0. ], + [-0.10050378, 1.00503781, 0. , 0. ], + [ 0. , 0. , 1. , 0. ], + [ 0. , 0. , 0. , 1. ]]) + + >>> transformation_matrix(19979245.2) + array([[ 1.00222811, -0.06679208, 0. , 0. ], + [-0.06679208, 1.00222811, 0. , 0. ], + [ 0. , 0. , 1. , 0. ], + [ 0. , 0. , 0. , 1. ]]) + + >>> transformation_matrix(1) + array([[ 1.00000000e+00, -3.33564095e-09, 0.00000000e+00, + 0.00000000e+00], + [-3.33564095e-09, 1.00000000e+00, 0.00000000e+00, + 0.00000000e+00], + [ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, + 0.00000000e+00], + [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, + 1.00000000e+00]]) + + >>> transformation_matrix(0) Traceback (most recent call last): ... ValueError: Speed must be greater than 1! - >> transformation_matrix(c * 1.5) + >>> transformation_matrix(c * 1.5) Traceback (most recent call last): ... ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]! From 9c7a85e6a307a71ddf51fabd0590d47880343f4a Mon Sep 17 00:00:00 2001 From: avivfaraj Date: Mon, 18 Apr 2022 09:09:12 -0400 Subject: [PATCH 45/45] Fixed tests on beta and gamma functions --- physics/lorenz_transformation_four_vector.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/physics/lorenz_transformation_four_vector.py b/physics/lorenz_transformation_four_vector.py index 12aef4845b88..6c0d5f9d1997 100644 --- a/physics/lorenz_transformation_four_vector.py +++ b/physics/lorenz_transformation_four_vector.py @@ -53,8 +53,8 @@ def beta(velocity: float) -> float: >>> beta(199792458) 0.666435904801848 - >> beta(1e5) - 4.5031152851750526e-07 + >>> beta(1e5) + 0.00033356409519815205 >>> beta(0.2) Traceback (most recent call last): @@ -72,19 +72,19 @@ def beta(velocity: float) -> float: def gamma(velocity: float) -> float: """ - >> gamma(4) + >>> gamma(4) 1.0000000000000002 - >> gamma(1e5) + >>> gamma(1e5) 1.0000000556325075 - >> gamma(3e7) + >>> gamma(3e7) 1.005044845777813 - >> gamma(2.8e8) + >>> gamma(2.8e8) 2.7985595722318277 - >> gamma(299792451) + >>> gamma(299792451) 4627.49902669495 >>> gamma(0.3)