Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. from matplotlib import pyplot as plt
  2. import numpy as np
  3.  
  4. def f(x):
  5.     return x**2
  6.  
  7. """calculate normal at x"""
  8. def get_normal(f, x):
  9.     dx = 0.05
  10.     dy = f(x+dx)-f(x)
  11.     length = (dx**2+dy**2)**0.5
  12.     return dy/length,-dx/length
  13.  
  14. """generate size # of points in range lower to upper"""
  15. def generate_points(f, lower, upper, size):
  16.     xs = lower + (upper-lower) * np.random.sample(size)
  17.     return xs, [f(x) for x in xs]
  18.  
  19. """
  20. apply noise on the x,y points (both are lists).
  21. size denotes the intensity of noise, should be trialed
  22. f is the function, needed for calculating the normal
  23. """
  24. def apply_noise(f, x, y, size):
  25.     xs = []
  26.     ys = []
  27.     for point in zip(x,y):
  28.         dx, dy = get_normal(f, point[0])
  29.         xs.append(point[0]+dx*size*np.random.randn(1))
  30.         ys.append(point[1]+dy*size*np.random.randn(1))
  31.     return xs, ys
  32.  
  33. if __name__=='__main__':
  34.     x, y = generate_points(f, 0, 1, 100) # generate points
  35.     plt.scatter(x, y, color='b') # plot in blue
  36.     x, y = apply_noise(f, x, y, 0.08) # apply noises
  37.     plt.scatter(x, y, color='r') # plot in red
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement