MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / next_point

Function next_point

project_euler/problem_144/sol1.py:35–75  ·  view source on GitHub ↗

Given that a laser beam hits the interior of the white cell at point (point_x, point_y) with gradient incoming_gradient, return a tuple (x,y,m1) where the next point of contact with the interior is (x,y) with gradient m1. >>> next_point(5.0, 0.0, 0.0) (-5.0, 0.0, 0.0) >>> ne

(
    point_x: float, point_y: float, incoming_gradient: float
)

Source from the content-addressed store, hash-verified

33
34
35def next_point(
36 point_x: float, point_y: float, incoming_gradient: float
37) -> tuple[float, float, float]:
38 """
39 Given that a laser beam hits the interior of the white cell at point
40 (point_x, point_y) with gradient incoming_gradient, return a tuple (x,y,m1)
41 where the next point of contact with the interior is (x,y) with gradient m1.
42 >>> next_point(5.0, 0.0, 0.0)
43 (-5.0, 0.0, 0.0)
44 >>> next_point(5.0, 0.0, -2.0)
45 (0.0, -10.0, 2.0)
46 """
47 # normal_gradient = gradient of line through which the beam is reflected
48 # outgoing_gradient = gradient of reflected line
49 normal_gradient = point_y / 4 / point_x
50 s2 = 2 * normal_gradient / (1 + normal_gradient * normal_gradient)
51 c2 = (1 - normal_gradient * normal_gradient) / (
52 1 + normal_gradient * normal_gradient
53 )
54 outgoing_gradient = (s2 - c2 * incoming_gradient) / (c2 + s2 * incoming_gradient)
55
56 # to find the next point, solve the simultaeneous equations:
57 # y^2 + 4x^2 = 100
58 # y - b = m * (x - a)
59 # ==> A x^2 + B x + C = 0
60 quadratic_term = outgoing_gradient**2 + 4
61 linear_term = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x)
62 constant_term = (point_y - outgoing_gradient * point_x) ** 2 - 100
63
64 x_minus = (
65 -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term)
66 ) / (2 * quadratic_term)
67 x_plus = (
68 -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term)
69 ) / (2 * quadratic_term)
70
71 # two solutions, one of which is our input point
72 next_x = x_minus if isclose(x_plus, point_x) else x_plus
73 next_y = point_y + outgoing_gradient * (next_x - point_x)
74
75 return next_x, next_y, outgoing_gradient
76
77
78def solution(first_x_coord: float = 1.4, first_y_coord: float = -9.6) -> int:

Callers 1

solutionFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected