9 ms·
In general, pretty cool stuff. There's no need to use Sympy, it's kind of overkill. If f(x) = 1/x^2 - a, then f'(x) = -2x^-3. You can find x_new easily: x_n
by csense 6y ago
In general, pretty cool stuff.
There's no need to use Sympy, it's kind of overkill. If f(x) = 1/x^2 - a, then f'(x) = -2x^-3. You can find x_new easily:
x_new = x - f(x) / f'(x)
= x - (1/x^2 - a) / (-2x^-3)
= x + (1/2) (x^3) (1/x^2 - a)
= x + (1/2) (x - ax^3)
= (3x - ax^3) / 2
= x(3 - ax^2) / 2
- a1k0n 6y agoYeah, that one wasn't too hard but it's nice to have it to check your work. I didn't go into it in the post, but the real power of SymPy is its cse() function, which I used to do all the common subexpression elimination for the integer math version at the bottom.
- Donald 6y agodo you have an example?
- creata 6y agoYou can find a small example for generating CSE'd C code for a sympy expression at https://stackoverflow.com/questions/22665990/optimize-code-generated-by-sympy https://stackoverflow.com/questions/22665990/optimize-code-g... . I think the built-in code generator is a bit strange, though: for example, it always prints integers as integers, and not as floats depending on the context, so code often doesn't typecheck.
- a1k0n 6y agoI tweeted a screenshot of the Jupyter Notebook session I used to create the code at the bottom: https://twitter.com/a1k0n/status/1301261285800030208 https://twitter.com/a1k0n/status/1301261285800030208