Skip to content

Instantly share code, notes, and snippets.

@josephcagle
Last active November 29, 2023 23:38
Show Gist options
  • Save josephcagle/9fa3ce1e7e6eeba9ea4a3838eb066df0 to your computer and use it in GitHub Desktop.
Save josephcagle/9fa3ce1e7e6eeba9ea4a3838eb066df0 to your computer and use it in GitHub Desktop.
Graph stuff in Python ASAP

Python math and function graphing, ASAP

  1. Make sure python3 and pip3 are installed
  2. Run pip3 install matplotlib numpy sympy
  3. Throw this other gist in a file (call it "domath.py" or something).
  4. Run python3 -i domath.py to run the script and continue in an interactive shell.
  5. You're done! (Well, done setting up, at least.)
  6. To actually do stuff with this, you can use the helper functions from that gist:
  • The plot_it function will plot the graph of a function, taking these arguments:
    • x_begin and x_end - The horizontal start and end values of your graph
    • *funcs - Zero or more functions to graph (use lambda expressions or references to function objects)
    • step (optional, named arg; default 0.0001) - The x distance between points on a graph. (Obviously, we can't plot the infinite number of points in a graph, so we choose a small step size to approximate it.)
    • equalize_axes (optional, named arg; default False) - Whether to force the graph to have equal scales on the x- and y-axes (default False)
  • (Also, we've imported everything from the math module, so you can simply type stuff like sqrt() and log10().)
  • The sci() function formats a number in scientific notation.
  • The factorize() function finds a whole number's prime factors.
    • (This runs in linear time proportional to the largest prime factor. There could be room for optimization, but for now, avoid factorizing numbers with large prime factors.)
  • There are also other helpers for trigonometry (sec, csc, cot).
  1. Here are some examples:
  • To get the value 0.00000012in scientific notation:
>>> sci(0.00000012)
'1.200000e-07'
  • Here is an example of plotting two different functions, using lambdas and function references:
>>> plot_it(0, 10, sin, lambda x: x**2/20)
  • Use the optional equalize_axes named argument to plot_it to make the graph have equal x- and y-axis scales. Try this to see the difference:
>>> plot_it(0, 10, lambda x: x**2)
>>> plot_it(0, 10, lambda x: x**2, equalize_axes=True)

You can also use the other stuff I put in there for chemistry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment