Implementation of the Golden Segmentation Method in python

Source: Internet
Author: User
Tags scalar

Implementation of the Golden Segmentation Method in python

This article mainly introduces the implementation of the Golden division method in python, involving the related skills of Python mathematical computation. For more information, see

?

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

'''A, B = bracket (f, xStart, h)

Finds the brackets (a, B) of a minimum point of

User-supplied scalar function f (x ).

The search starts downhill from xStart with a step

Length h.

X, fMin = search (f, a, B, tol = 1.0e-6)

Golden section method for determining x that minimizes

The user-supplied scalar function f (x ).

The minimum must be bracketed in (a, B ).

'''

From math import log, ceil

Def bracket (f, x1, h ):

C = 1.618033989.

F1 = f (x1)

X2 = x1 + h; f2 = f (x2)

# Determine downhill direction and change sign of h if needed

If f2> f1:

H =-h

X2 = x1 + h; f2 = f (x2)

# Check if minimum between x1-h and x1 + h

If f2> f1: return x2, x1-h

# Search loop

For I in range (100 ):

H = c * h

X3 = x2 + h; f3 = f (x3)

If f3> f2: return x1, x3

X1 = x2; x2 = x3

F1 = f2; f2 = f3

Print "Bracket did not find a mimimum"

Def search (f, a, B, tol = 1.0e-9 ):

NIter = int (ceil (-2.078087 * log (tol/abs (B-a) # Eq. (10.4)

R = 0.618033989.

C = 1.0-R

# First telescoping

X1 = R * a + C * B; x2 = C * a + R * B

F1 = f (x1); f2 = f (x2)

# Main loop

For I in range (nIter ):

If f1> f2:

A = x1

X1 = x2; f1 = f2

X2 = C * a + R * B; f2 = f (x2)

Else:

B = x2

X2 = x1; f2 = f1

X1 = R * a + C * B; f1 = f (x1)

If f1 <f2: return x1, f1

Else: return x2, f2

I hope this article will help you with Python programming.

Note <>: For more exciting tutorials, please pay attention to the help house programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.