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

Function intersection

maths/numerical_analysis/intersection.py:5–41  ·  view source on GitHub ↗

function is the f we want to find its root x0 and x1 are two random starting points >>> intersection(lambda x: x ** 3 - 1, -5, 5) 0.9999999999954654 >>> intersection(lambda x: x ** 3 - 1, 5, 5) Traceback (most recent call last): ... ZeroDivisionError: float divis

(function: Callable[[float], float], x0: float, x1: float)

Source from the content-addressed store, hash-verified

3
4
5def intersection(function: Callable[[float], float], x0: float, x1: float) -> float:
6 """
7 function is the f we want to find its root
8 x0 and x1 are two random starting points
9 >>> intersection(lambda x: x ** 3 - 1, -5, 5)
10 0.9999999999954654
11 >>> intersection(lambda x: x ** 3 - 1, 5, 5)
12 Traceback (most recent call last):
13 ...
14 ZeroDivisionError: float division by zero, could not find root
15 >>> intersection(lambda x: x ** 3 - 1, 100, 200)
16 1.0000000000003888
17 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 0, 2)
18 0.9999999998088019
19 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 2, 4)
20 2.9999999998088023
21 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 4, 1000)
22 3.0000000001786042
23 >>> intersection(math.sin, -math.pi, math.pi)
24 0.0
25 >>> intersection(math.cos, -math.pi, math.pi)
26 Traceback (most recent call last):
27 ...
28 ZeroDivisionError: float division by zero, could not find root
29 """
30 x_n: float = x0
31 x_n1: float = x1
32 while True:
33 if x_n == x_n1 or function(x_n1) == function(x_n):
34 raise ZeroDivisionError("float division by zero, could not find root")
35 x_n2: float = x_n1 - (
36 function(x_n1) / ((function(x_n1) - function(x_n)) / (x_n1 - x_n))
37 )
38 if abs(x_n2 - x_n1) < 10**-5:
39 return x_n2
40 x_n = x_n1
41 x_n1 = x_n2
42
43
44def f(x: float) -> float:

Callers 1

intersection.pyFile · 0.85

Calls 1

functionFunction · 0.85

Tested by

no test coverage detected