-
Notifications
You must be signed in to change notification settings - Fork 1
/
OneDimensionalNewtonMethod.py
77 lines (40 loc) · 1.76 KB
/
OneDimensionalNewtonMethod.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from Method import Method
from Derivative import Derivative
class OneDimensionalNewtonMethod():
def __init__( self , function = None ):
self.epsilon = Method.epsilon
self.maxIterations = 150
self.function = function
self.firstDerivative = Derivative( n = 1, dx = 0.00001 )
self.secondDerivative = Derivative( n = 2, dx = 0.00001 )
self.current = [ 0 , 3 ]
self.direction = [ 0 , 3 ]
def setCurrent( self, current ):
self.current = current
def setDirection( self, direction ):
self.direction = direction
def optimize( self, x ) :
self.firstDerivative.setFunction( self.functionToOptimize() )
self.secondDerivative.setFunction( self.functionToOptimize() )
for k in range( self.maxIterations ) :
p = x
try:
x = x - ( self.firstDerivative.derivative( x ) / self.secondDerivative.derivative( x ) )
except ZeroDivisionError as error:
return x
e = x - p
if e < 0 :
e = e * - 1
if e < self.epsilon :
break
return x
def functionToOptimize( self ):
def f( x ):
return self.function( self.current[0] + ( self.direction[ 0 ] * x ), self.current[1] + ( self.direction[ 1 ] * x ) )
return f
def setFunction( self, function ):
self.function = function
def setFirstDerivative( self, firstDerivative ):
self.firstDerivative = firstDerivative
def setSecondDerivative( self, secondDerivative ):
self.secondDerivative = secondDerivative