nivs

Untitled

Feb 24th, 2014
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.79 KB | None | 0 0
  1. import math
  2. from multiprocessing import Process
  3.  
  4. import numpy
  5. from matplotlib import pyplot as plt
  6.  
  7.  
  8. x_start, x_finish, x_delta = -100, 100, 0.1
  9.  
  10.  
  11. class Linear():
  12.     def __init__(self, a, b):
  13.         self.a = a
  14.         self.b = b
  15.  
  16.     def value(self, x):
  17.         return self.a * x + self.b
  18.  
  19.     def derivative(self, *args):
  20.         return self.a
  21.  
  22.  
  23. class Sinus():
  24.     def __init__(self):
  25.         pass
  26.  
  27.     def value(self, x):
  28.         return math.sin(x)
  29.  
  30.     def derivative(self, x):
  31.         return math.cos(x)
  32.  
  33.  
  34. class Cosinus():
  35.     def __init__(self):
  36.         pass
  37.  
  38.     def value(self, x):
  39.         return math.cos(x)
  40.  
  41.     def derivative(self, x):
  42.         return math.sin(x)
  43.  
  44.  
  45. class Superposition():
  46.     def __init__(self, f, g):
  47.         self.f = f
  48.         self.g = g
  49.  
  50.     def value(self, x):
  51.         return self.f.value(self.g.value(x))
  52.  
  53.     def derivative(self, x):
  54.         return self.f.derivative(self.g.value(x)) * self.g.derivative(x)
  55.  
  56.  
  57. class Power():
  58.     def __init__(self, a):
  59.         self.a = a
  60.  
  61.     def value(self, x):
  62.         return math.pow(x, self.a)
  63.  
  64.     def derivative(self, x):
  65.         return self.a * math.pow(x, self.a-1)
  66.  
  67.  
  68. def isfloat(var):
  69.     try:
  70.         float(var)
  71.         return True
  72.     except ValueError:
  73.         return False
  74.  
  75.  
  76. def input_float(msg):
  77.     while True:
  78.         ret = input(msg)
  79.         if not isfloat(ret):
  80.             print("Параметр введён некорректно, повторите ввод\n")
  81.         else:
  82.             return float(ret)
  83.  
  84.  
  85. def plot_back(class_, seg):
  86.     segment = numpy.linspace(seg[0], seg[1], (seg[1] - seg[0]) / seg[2])
  87.  
  88.     fig = plt.figure()
  89.     fig.suptitle("   " + class_.__class__.__name__ + '\n', fontsize=20, )
  90.  
  91.     plt.subplot(2, 1, 1)
  92.     plt.title("Function")
  93.     plt.xlabel("X")
  94.     plt.ylabel("Y")
  95.     plt.grid(color='g', linestyle='--')
  96.     x = segment
  97.     y = [class_.value(i) for i in segment]
  98.     plt.axis([seg[0] - (seg[1] - seg[0])*0.02,
  99.               seg[1] + (seg[1] - seg[0])*0.02,
  100.               min(y) - (max(y) - min(y))*0.06,
  101.               max(y) + (max(y) - min(y))*0.06])
  102.     plt.plot(x, y, "r-", linewidth=2.0)
  103.  
  104.     plt.subplot(2, 1, 2)
  105.     plt.title("Derivative")
  106.     plt.xlabel("X")
  107.     plt.ylabel("Y'")
  108.     plt.grid(color='g', linestyle='--')
  109.     y = [class_.derivative(i) for i in segment]
  110.     plt.axis([seg[0] - (seg[1] - seg[0])*0.02,
  111.               seg[1] + (seg[1] - seg[0])*0.02,
  112.               min(y) - (max(y) - min(y))*0.06,
  113.               max(y) + (max(y) - min(y))*0.06])
  114.     plt.plot(x, y, "r-", linewidth=2.0)
  115.     plt.show()
  116.  
  117.  
  118. def plot(class_, seg):
  119.     Process(target=plot_back, args=(class_, seg,)).start()
  120.  
  121.  
  122. def interactive_plot(class_):
  123.     global x_start, x_finish, x_delta
  124.     print("Построение графиков.\n"
  125.           "Текущие параметры:\n"
  126.           "X начальное: " + str(x_start) + "\n"
  127.           "X конечное : " + str(x_finish) + "\n"
  128.           "Шаг X      : " + str(x_delta) + "\n")
  129.     while True:
  130.         ans = input("Хотите использовать текущие параметры? Y/n || Д/н: ")
  131.         if ans == 'n' or ans == "н" or \
  132.                 ans == 'N' or ans == "Н":
  133.             x_start = input_float("Введите X начальное: ")
  134.             x_finish = input_float("Введите X конечное : ")
  135.             x_delta = input_float("Введите шаг        : ")
  136.         elif ans == 'y' or ans == "д" or \
  137.                 ans == 'Y' or ans == "Д" or ans == "":
  138.             break
  139.     plot(class_, (x_start, x_finish, x_delta))
  140.  
  141.  
  142. while True:
  143.     print("1. Линейная\n"
  144.           "2. Синус\n"
  145.           "3. Косинус\n"
  146.           "4. Суперпозиция\n"
  147.           "5. Степенная функция\n")
  148.     number_of_func = input_float("Введите номер желаемой функции: ")
  149.     if number_of_func == 1.0:
  150.         interactive_plot(Linear(input_float("Введите параметр a: "),
  151.                                 input_float("Введите параметр b: ")))
  152.     elif number_of_func == 2.0:
  153.         interactive_plot(Sinus())
  154.     elif number_of_func == 3.0:
  155.         interactive_plot(Cosinus())
  156.     elif number_of_func == 4.0:
  157.         # while True:
  158.         #     ans = input_float("Выбирете функцию f:\n"
  159.         #                       "1. Линейная\n"
  160.         #                       "2. Синус\n"
  161.         #                       "3. Косинус\n"
  162.         #                       "4. Степенная функция\n")
  163.         # interactive_plot(Superposition())
  164.         pass
  165.     elif number_of_func == 5.0:
  166.         interactive_plot(Power(input_float("Введите параметр a: ")))
  167.     print("\n")
Advertisement
Add Comment
Please, Sign In to add comment