integral.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from pysketcher import *
  2. def f(x):
  3. return 3*np.exp(-x**4)
  4. xmin = -2
  5. drawing_tool.set_coordinate_system(xmin=xmin, xmax=4,
  6. ymin=0, ymax=4,
  7. axis=True, xkcd=True)
  8. drawing_tool.set_linecolor('blue')
  9. import numpy as np
  10. x = np.linspace(xmin, 3, 201)
  11. y = f(x)
  12. curve = Curve(x, y)
  13. x2 = np.linspace(xmin, 0.2, 201)
  14. y2 = f(x2)
  15. x2 = x2.tolist()
  16. y2 = y2.tolist()
  17. x2.append(x2[-1])
  18. y2.append(0)
  19. x2.append(xmin)
  20. y2.append(0)
  21. #x2 = np.array(x2)
  22. #y2 = np.array(y2)
  23. filled = Curve(x2, y2).set_filled_curves(pattern='/')
  24. text1 = Text_wArrow('The integral $\int_{-\infty}^{0.2} 3e^{-x^4}dx$\nis impossible to calculate\nby hand but so easy with\na program!', (1.5, 3.5), (-0.2, 1), alignment='left')
  25. fig = Composition(dict(curve=curve, integral=filled, comment=text1))
  26. fig.draw()
  27. drawing_tool.display()
  28. drawing_tool.savefig('tmp1')
  29. #raw_input()
  30. # Draw piecewise curve for midpoint rule
  31. def piecewise_curve_for_midpoint_rule(N):
  32. dx = (0.2 - xmin)/float(N)
  33. x3_double = []
  34. y3_double = []
  35. y_prev = 0
  36. for i in range(N):
  37. x = xmin + i*dx
  38. x3_double.append(x)
  39. y3_double.append(y_prev)
  40. x3_double.append(x)
  41. y_next = 0.5*(f(x) + f(xmin+(i+1)*dx))
  42. y3_double.append(y_next)
  43. y_prev = y_next
  44. x = xmin + (i+1)*dx
  45. x3_double.append(x)
  46. y3_double.append(y_prev)
  47. x3_double.append(x)
  48. y3_double.append(0)
  49. # Back to start
  50. x3_double.append(xmin)
  51. y3_double.append(0)
  52. midpoint_curve = Curve(x3_double, y3_double).set_filled_curves(pattern='/').set_linecolor('red')
  53. return midpoint_curve
  54. text2 = Text_wArrow('We just draw some rectangles\nto approximate the area\nunder the curve and sum up\nthe rectangular areas!', (1.2, 3.5), (-0.2, 1), alignment='left')
  55. drawing_tool.erase()
  56. fig = Composition(dict(curve=curve, integral=piecewise_curve_for_midpoint_rule(N=4), comment=text2))
  57. fig.draw()
  58. drawing_tool.display()
  59. drawing_tool.savefig('tmp2')
  60. text3 = Text_wArrow('Just add more rectangles\ngo get the integral\nmore accurate!', (1.5, 3.5), (-0.2, 1), alignment='left')
  61. drawing_tool.erase()
  62. fig = Composition(dict(curve=curve, integral=piecewise_curve_for_midpoint_rule(N=10), comment=text3))
  63. fig.draw()
  64. drawing_tool.display()
  65. drawing_tool.savefig('tmp3')
  66. import os
  67. os.system('doconce combine_images pdf -3 tmp1 tmp2 tmp3 integral_comic_strip')
  68. os.system('doconce combine_images png -3 tmp1 tmp2 tmp3 integral_comic_strip')
  69. raw_input()