Advertisement
ms_shnits

Метод наименьших квадратов

Oct 21st, 2018
769
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.07 KB | None | 0 0
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. #https://otvet.mail.ru/question/211063944
  5.  
  6. #python 3.5.2
  7.  
  8. from math import pi, sin
  9. from random import uniform
  10.  
  11. # задаем модельные значения параметров:
  12. A, B = 10.0, 0.4
  13.  
  14. # задаём модельную функцию
  15. f = lambda x, a, b : a*sin(b*x)
  16.  
  17. # задаём шаг дискретной сетки на интервале x = 0...2*pi
  18. h = 0.5
  19.  
  20. # задаём амплитуду "погрешностей"
  21. distortion = 0.5
  22.  
  23. # рассчитываем модельные значения функции y = a * sin(b * x)
  24. model = tuple( (i*h, f(i*h, A, B)) for i in range(0, int(2*pi/h)+1) )
  25.  
  26. # рассчитываем "экспериментальные" значения (модельные значения с погрешностями)
  27. data = tuple( (x, y + uniform(-distortion, distortion)) for x, y in model )
  28.  
  29. # выводим модель на экран
  30. print ("--- начальные данные ---")
  31. print ("Модельные значения параметров: A = %f, B = %f" % (A, B) )
  32. print ("Значения модельной функции y = A sin (b x) и \"экспериментальные\" данные (y~):")
  33. print ("\n".join("x = %f\ty = %e\ty~=%e" % (m[0], m[1], d[1]) for m, d in zip(model, data)))
  34.  
  35.  
  36. # рассчитываем значения параметров по экспериментальным данным
  37. print ("--- расчет ---")
  38.  
  39. # начальное приближение
  40. a, b = 5.0, 1.0
  41.  
  42. # целевая функция по МНК
  43. F = lambda a, b, data: sum( (y - f(x, a, b))**2 for x, y in data )
  44.  
  45. total_iterations = 0
  46.  
  47. shift = 1.
  48. for i in range(6):
  49.  
  50.     shift *= 1e-1
  51.     print ("итерации с шагом %f" % shift)
  52.  
  53.     shifts = (
  54.         (   0.0,    0.0),
  55.         (-shift, -shift),
  56.         (   0.0, -shift),
  57.         ( shift, -shift),
  58.         ( shift,    0.0),
  59.         ( shift,  shift),
  60.         (   0.0,  shift),
  61.         (-shift,  shift),
  62.         (-shift,    0.0)
  63.         )
  64.  
  65.     iteration = 0
  66.     choices = tuple(F(a+shA, b+shB, data) for shA, shB in shifts)
  67.     choice = choices.index(min(choices))
  68.     while choice != 0 and iteration < 1000:
  69.         a += shifts[choice][0]
  70.         b += shifts[choice][1]
  71.         if not iteration % 10:
  72.             print ("итерация %d\tA = %f\tB = %f\tцелевая функция = %e" % (iteration, a, b, choices[choice]))
  73.         iteration += 1
  74.         choices = tuple(F(a+shA, b+shB, data) for shA, shB in shifts)
  75.         choice = choices.index(min(choices))
  76.     print ("итерация %d\tA = %f\tB = %f\tцелевая функция = %e" % (iteration-1, a, b, choices[choice]))
  77.     total_iterations += iteration
  78.  
  79. # вывод результата
  80. print ("--- результат расчета ---")
  81. print ("Вычисленные значения параметров: A = %f, B = %f" % (a, b) )
  82. print ("Значение целевой функции МНК: %e" % F(a, b, data) )
  83. print ("Количество итераций: %d" % total_iterations )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement