Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to draw Koch Curve

2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to use Python to draw Koch curve", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to draw Koch curve with Python.

1. Recursive 1.1 definition

As a kind of code encapsulation, a function can be called by other programs or, of course, by the internal code of the function. The way in which the function itself is called in this function definition is called recursion. It's like a person standing in a room full of mirrors, and the image you see is the result of recursion. Recursion is very powerful in mathematics and computer applications, and can solve important problems very succinctly.

In mathematics, there is a classic recursive example called factorial, which is usually defined as follows:

N = n (n-1) (n-2)... (1)

To implement this program, you can calculate the factorial through a simple loop accumulation. Watch 5! If you get rid of 5, then you will be left with a calculation of 4%. From a generalization point of view, we will find that there is no more than 5%. In fact, this relationship gives another way to express factorial:

When n = 0, n! = 1; otherwise, n! = n (n-1)!

This definition states that the factorial of 0 is defined as 1, and the factorial of other numbers is defined as this number multiplied by a factorial 1 less than this number. Recursion is not a loop because each recursion calculates a factorial that is smaller than it until 0!. 0! Is a known value and is called a base example of recursion. When recursive to the end, you need an expression that can calculate the value directly.

The factorial example reveals two key features of recursion:

(1) there are one or more base examples, which do not need to be recursive again, it is a definite expression.

(2) all recursive chains should end with one or more base examples.

1.2 Mathematical induction

Both mathematical induction and recursion make use of the recursive principle and are essentially the same. In proving a proposition P (n) related to natural numbers, mathematical induction takes the following steps.

(1) prove that the proposition holds when n takes the first value n0.

(2) suppose that the proposition is true when nk (k ≥ 0, k is a natural number), and prove that the proposition is also true when n=nk+1.

Combining (1) and (2), proposition P (n) holds for all natural numbers n (n ≥ N0).

two。 The use of recursion 2.1 factorial

Take the factorial calculation as an example, you can write the factorial as a separate function, then the function is as follows:

Def fact (n): if n = = 0: return 1 else: return n * fact (n-1) num = eval (input ("Please enter an integer:") print (fact (int (num)

The fact () function references itself within its definition, forming a recursive procedure (such as line 5). Unlimited recursion will run out of computing resources, so you need to design a base example to make recursion return layer by layer. The fact () function gives the base example when n is 0 through the if statement. When the n is no longer recursive, the function returns the value 1. If the n is equal to 0, the product of n and the factorial of n is returned recursively.

Since negative numbers and decimals cannot reach the recursive base example (n = 0) by minus 1, line 8 of the code converts user input to non-negative integers through the abs () and int () functions, and the output of the program is as follows:

Please enter an integer: 5

one hundred and twenty

Please enter an integer: 6.789

seven hundred and twenty

Recursion follows the semantics of the function, and each call causes the start of a new function, indicating that it has a copy of the local variable value, including the function's parameters. Each time the function is called, the copy of the function parameters is stored temporarily, and each function calculates its own parameters in recursion, which has no influence on each other. When the base example ends the operation and returns a value, each function ends the operation layer by layer and returns the calculation result to the caller.

Be sure to pay attention to the construction of the base case when using recursion, otherwise an error will be reported if the recursion cannot be returned.

2.2 string inversion

For the string s entered by the user, the inverted string is output.

The basic idea to solve this problem is to treat a string as a recursive object. Long strings consist of shorter strings, and each small string is also an object. If you think of a string as consisting of only two parts: the first character and the remaining string. If you swap the remaining string with the first character, you are finished reversing the entire string, as follows:

Def reverse (s): return reverse ((s [1:]) + s [0])

Observe how this function works. S [0] is the first character, s [1:] is the rest of the string, reverse concatenation of them, you can get a reverse string. Execute this program, and the results are as follows:

Def reverse (s): return reverse (s [1:]) + s [0] reverse ("abc")

Return reverse (s [1:]) + s [0]

[Previous line repeated 996 more times]

RecursionError: maximum recursion depth exceeded

This error indicates that the system cannot perform the recursion created by the reverse () function because the reverse () function has no base example and the number of layers of recursion exceeds the maximum recursive depth allowed by the system. By default, when recursively called to layer 1000, the Python interpreter terminates the program. The recursion depth is designed to prevent infinite recursive errors. When the correct recursive program written by the user requires more than 1000 layers, it can be set by the following code:

Import syssys.setrecursionlimit (2000) # 2000 is the new number of recursive layers

Reverse () exceeds the recursive depth because there is no design base example. Recursive calls in string inversion always use a shorter string than before, so the base case can be designed as the shortest form of the string, the empty string.

The complete code is as follows:

Def reverse (s): if s = = "": return s else: return reverse (s [1:]) + s [0] str = input ("Please enter a string:") print (reverse (str))

The execution result of the program is as follows:

Please enter a string: Python programming

Program nohtyP

3. The drawing of Koch Curve 3.1 Summary

This is an example of using recursive method to draw Koch curve, and fractal geometry adopts the core idea similar to recursion.

There are many regular figures in nature, which conform to certain mathematical laws. For example, honeybee hives are naturally equilateral hexagons and so on. Koch curve is very famous among many classical mathematical curves, by Swedish mathematician Feng. H-V-Koch proposed in 1904, because its shape is similar to the snowflake, also known as the snowflake curve.

The basic concepts and drawing methods of Koch curve are as follows:

The positive integer n represents the order of the Koch curve and the number of operations in the process of generating the Koch curve. The initialization degree of the Koch curve is 0, which represents a straight line of length L. For the straight line L, it is equally divided into three segments, and the middle segment is replaced by two sides of an equilateral triangle with a length of L _ stroke 3, and a Koch curve of order 1 is obtained, which contains four segments. After repeating the same operation for each segment, the Koch curve of order 2 is obtained. Continue to repeat the same operation n times to get a Koch curve of order n, as shown in the following figure:

3.2 draw Koch curve

Koch curve belongs to the branch of fractal geometry, and its drawing process embodies the recursive idea. The drawing process code is as follows:

Import turtledef koch (size, n): if n = 0: turtle.fd (size) else: for angle in [0,60,120,60]: turtle.left (angle) koch (size / 3,n-1) def main (): turtle.setup (800,400) turtle.speed (0) # Control rendering speed turtle.penup () turtle.goto -50) turtle.pendown () turtle.pensize (2) koch (600,6) # 0 Koch curve length Degree turtle.hideturtle () main ()

The execution result of the program is as follows:

The drawing of n-order Koch curve is equivalent to drawing Nmuri 1-order curve at 0 °, 60 °,-120 °and 60 °of the forward direction of the brush, respectively. The main () function in the above code sets some initial parameters, and if you want to control the speed of drawing the Koch curve, you can use the turtle.speed () function to increase or decrease the speed.

3.3 Snowflake effect of Koch curve

The Koch curve starts with a straight line, and it will be more interesting if it starts with an inverted triangle. Replace the main () function in the previous code, as follows:

Import turtledef koch (size, n): if n = 0: turtle.fd (size) else: for angle in [0,60,120,60]: turtle.left (angle) koch (size / 3,n-1) def main (): turtle.setup (600,600) turtle.speed (1000) turtle.penup () turtle.goto Turtle.pendown () turtle.pensize (2) level = 5 koch (400, level) turtle.right (120) koch (400, level) turtle.right (120) koch (400, level) turtle.hideturtle () main ()

The execution result of the program is as follows:

3.4 Fractal geometry

Fractal geometry is a branch of mathematics, which takes irregular geometry as the research object. Based on the self-similar structure, fractals show the internal mathematical order under the complex surface by infinite recursion. Fractal geometry not only shows the beauty of mathematics, but also reveals the essence of the world, which makes people re-examine the world: the world is nonlinear and fractals are everywhere.

At this point, I believe you have a deeper understanding of "how to use Python to draw Koch curve". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 266

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report