@PythonStudent

Распараллеливание в python, возможно ли?

Добрый день, имеется программа написанная на python, которая выполняет построение кривой Госпера и на большом количестве итераций - 7, 8, программа работает заметно долго. Необходимо предоставить параллельный вариант, чтобы удовлетворить условию - ускорить скорость построения фрактала при случаях с n итераций = 7, 8, хотя бы в 2 раза. Подскажите, в какую сторону смотреть и есть ли смысл пытаться реализовать это на python?

UPD, код программы:
import matplotlib.pyplot as plt
import numpy as np
import math
from PIL import Image
from math import sin, cos, atan2, radians

class turtle:
    def __init__(self):
        self._direction = np.array([1, 0]) # 2D direction vector
        self._position = np.array([0, 0]) # 2D position vector
    def forward(self):
        pos = self._position
        dirn = self._direction
        self._position = np.add(pos, dirn)
    def rotate(self, theta):
        (x, y) = self._direction
        current_angle = atan2(y, x)
        new_angle = current_angle + radians(theta)
        self._direction = [cos(new_angle), sin(new_angle)]

def L_system(commands, axiom, production_rules, theta, n_iterations):
    command_string = axiom # Begin commands with only the axiom
    for iteration in range(n_iterations):
        new_command_string = str()
        for char in command_string:
            if char in production_rules:
                new_command_string += production_rules[char]
            else:
                new_command_string += char
        command_string = new_command_string

    n_commands = len(command_string) # Total number of commands for the turtle

    t = turtle() # Initialize a turtle at position [0, 0]

    positions = np.zeros((n_commands, 2))

    for i, command in enumerate(command_string):
        if command in commands:
            exec(commands[command]) # Perform command on turtle
        positions[i, :] = t._position

    return positions

# Alghoritm for Gosper curve (commands, axiom, rules, number of iterations and angle)
commands = {
    'A': 't.forward()',
    'B': 't.forward()',
    '+': 't.rotate(theta)',
    '-': 't.rotate(-theta)',
    }
axiom = 'A'
production_rules = {
    'A': '+-A-B--B+A++AA+B-',
    'B': '+A-BB--B-A++A+B'
    }
theta = 60

n_iterations = int(input("Введите Количество итераций: "));
angle = int(input("Введите угол наклона: "));
positions = L_system(commands, axiom, production_rules, theta, n_iterations)
pointX = int(input("Введите точку по оси Х: "));
pointY = int(input("Введите точку по оси Y: "));

def rotate_origin_only(positions, pointX, pointY, angle):
    x = positions[:, 0] + pointX
    y = positions[:, 1] + pointY
    xx = x * math.cos(angle) + y * math.sin(angle)
    yy = -x * math.sin(angle) + y * math.cos(angle)
    return xx, yy

xx, yy = rotate_origin_only (positions, pointX, pointY, angle)
plt.plot(xx, yy)
plt.savefig('out.jpg')
plt.show()
  • Вопрос задан
  • 149 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы