<?xml version="1.0" encoding="UTF-8"?>

<rss version="2.0"
     xmlns:content="http://purl.org/rss/1.0/modules/content/"
     xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
     xmlns:atom="http://www.w3.org/2005/Atom"
     xmlns:dc="http://purl.org/dc/elements/1.1/"
     xmlns:wfw="http://wellformedweb.org/CommentAPI/"
     >
  <channel>
    <atom:link href="http://kitchingroup.cheme.cmu.edu/blog/feed/index.xml" rel="self" type="application/rss+xml" />
    <title>The Kitchin Research Group</title>
    <link>https://kitchingroup.cheme.cmu.edu/blog</link>
    <description>Chemical Engineering at Carnegie Mellon University</description>
    <pubDate>Sat, 01 Nov 2025 13:47:46 GMT</pubDate>
    <generator>Blogofile</generator>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    
    <item>
      <title>A partial symbolic numeric solver in emacs-lisp</title>
      <link>https://kitchingroup.cheme.cmu.edu/blog/2017/05/21/A-partial-symbolic-numeric-solver-in-emacs-lisp</link>
      <pubDate>Sun, 21 May 2017 11:33:15 EDT</pubDate>
      <category><![CDATA[math]]></category>
      <category><![CDATA[emacs]]></category>
      <category><![CDATA[emacs-lisp]]></category>
      <guid isPermaLink="false">yXBmBn5c2JK1DkEAlZuJewhh724=</guid>
      <description>A partial symbolic numeric solver in emacs-lisp</description>
      <content:encoded><![CDATA[


&lt;div id="table-of-contents"&gt;
&lt;h2&gt;Table of Contents&lt;/h2&gt;
&lt;div id="text-table-of-contents"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="#org18a4554"&gt;1. The Newton solver in emacs-lisp&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;
I have been exploring  ways to use emacs-lisp to express scientific ideas. In this post, we explore a partial symbolic numeric solver in Emacs-lisp. This involves some syntactic developments to more clearly identify something we want to solve for and to then generate the code required to solve it.
&lt;/p&gt;

&lt;p&gt;
In section &lt;a href="#org18a4554"&gt;The Newton solver&lt;/a&gt; you can find a simple implementation of a Newton solver in emacs-lisp. This function allows you to numerically solve equations that can be written in the form \(f(x) = 0\) for \(x\) given an initial guess. You write a function for \(f(x)\) and pass the function to the solver. This is a standard approach used in Python with fsolve, for example. Here is an example of solving a trivial problem: \(x - 4 = 0\) just to check that it works. We use a lambda function for \(f(x) = x - 4 = 0\). The answer is \(x=4\).
&lt;/p&gt;

&lt;div class="org-src-container"&gt;
&lt;pre class="src src-emacs-lisp"&gt;(newton-f (&lt;span style="color: #0000FF;"&gt;lambda&lt;/span&gt; (x) (- x 4)) 2)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
That syntax is not too bad, but we have the whole lambda expression in there, and some repetition of what we want to solve for as an argument and in the function. It would be interesting if we could just have an expression that gets solved, e.g. &lt;code&gt;(newton-f (- x? 4) 2)&lt;/code&gt; where &lt;code&gt;x?&lt;/code&gt; indicates the thing to solve for.
&lt;/p&gt;

&lt;p&gt;
We can do that! We can take an expression, flatten it and find the variable names that end with ?. We should check that there is only one, but for now we don't. Here is an example that does that. I use a nested expression here just to illustrate that the code finds the &lt;code&gt;x?&lt;/code&gt; variable correctly.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;
&lt;pre class="src src-emacs-lisp"&gt;(&lt;span style="color: #0000FF;"&gt;require&lt;/span&gt; '&lt;span style="color: #D0372D;"&gt;dash&lt;/span&gt;)

(&lt;span style="color: #0000FF;"&gt;let&lt;/span&gt; ((body '((* (- x? 4) 1))))
  (&lt;span style="color: #0000FF;"&gt;loop&lt;/span&gt; for item in (-flatten body)
        if (&lt;span style="color: #0000FF;"&gt;and&lt;/span&gt; (symbolp item) (s-ends-with? &lt;span style="color: #008000;"&gt;"?"&lt;/span&gt; (symbol-name item)))
        collect item))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
So, given an expression we can identify the unknown that should be the argument to a lambda function. So, we create a macro that takes that expression and constructs a function to solve it, then calls newton-f on it. The macro is syntactically useful here because we do not have to quote the expression. Here is that macro.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;
&lt;pre class="src src-emacs-lisp"&gt;(&lt;span style="color: #0000FF;"&gt;defmacro&lt;/span&gt; &lt;span style="color: #006699;"&gt;solve&lt;/span&gt; (expression guess)
  `(newton-f
    (&lt;span style="color: #0000FF;"&gt;lambda&lt;/span&gt; ,(&lt;span style="color: #0000FF;"&gt;loop&lt;/span&gt; for item in (-flatten expression)
                   if (&lt;span style="color: #0000FF;"&gt;and&lt;/span&gt; (symbolp item) (s-ends-with? &lt;span style="color: #008000;"&gt;"?"&lt;/span&gt; (symbol-name item)))
                   collect item)
      ,expression)
    ,guess))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
I call this a partial symbolic solver because we do some introspection symbolically to identify what to solve for, and then construct the code required to solve it. Here is that trivial example (x? - 4 = 0). It just shows we can have some nesting and it still works. I am not so thrilled with the initial guess, but this is an iterative solver, so you either need an initial guess, or a solution range.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;
&lt;pre class="src src-emacs-lisp"&gt;(&lt;span style="color: #0000FF;"&gt;solve&lt;/span&gt; (* (- x? 4) 1) 3)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Here is what that expands into:
&lt;/p&gt;

&lt;div class="org-src-container"&gt;
&lt;pre class="src src-emacs-lisp"&gt;(macroexpand '(solve (* (- x? 4) 1) 3))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
It expands into what we would have written in the first place. The benefit to us is less typing, and a simpler syntax. Both of those reduce the opportunity to make errors!
&lt;/p&gt;

&lt;p&gt;
A more realistic problem might be: Reactant A flows into a continuously stirred tank reactor at a rate of  \(F_{A0} = 1\) mol/min with a volumetric flow of \(v_0 = 1\) L/min.. The reactor achieves 50% conversion (\(X\)) of A to products. The reaction rate law is known to be \(-r_A = k C_A\) with \(k = 0.1\) 1/min. Estimate the volume of the reactor. If you have taken my class in reaction engineering, you know the following facts:
&lt;/p&gt;

&lt;ul class="org-ul"&gt;
&lt;li&gt;The exit molar flow is defined by \(F_A = F_{A0} (1 - X)\)&lt;/li&gt;
&lt;li&gt;The exit concentration is \(C_A = F_A / v_0\)&lt;/li&gt;
&lt;li&gt;The mole balance is defined by \(0 = F_{A0} - F_A + r_A V\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
That is all we need; we can solve for \(V\) from the last equation. This is simple enough you might do the algebra to get: \(V = \frac{F_{A0} - F_A}{-r_A}\) which can be simply evaluated. We use our solver here and compare it to the evaluation.
&lt;/p&gt;

&lt;p&gt;
Here is the solver:
&lt;/p&gt;

&lt;div class="org-src-container"&gt;
&lt;pre class="src src-emacs-lisp"&gt;(&lt;span style="color: #0000FF;"&gt;let*&lt;/span&gt; ((Fa0 1)
       (X 0.5)
       (Fa (* Fa0 (- 1 X)))
       (k 0.1)
       (v0 1)
       (Ca (/ Fa v0))
       (r (* k Ca))
       (ra (* r -1)))
  (&lt;span style="color: #0000FF;"&gt;solve&lt;/span&gt; (+ Fa0 (* Fa -1) (* ra V?)) 2))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
It is pretty hard to imagine doing something like this in Python! It would probably involve parsing a string.
&lt;/p&gt;

&lt;p&gt;
Here is the evaluation from our algebra:
&lt;/p&gt;

&lt;div class="org-src-container"&gt;
&lt;pre class="src src-emacs-lisp"&gt;(&lt;span style="color: #0000FF;"&gt;let*&lt;/span&gt; ((Fa0 1)
       (X 0.5)
       (Fa (* Fa0 (- 1 X)))
       (k 0.1)
       (v0 1)
       (Ca (/ Fa v0))
       (r (* k Ca))
       (ra (* r -1)))
  (/ (- Fa0 Fa) (* -1 ra)))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
Within the tolerance specified in &lt;code&gt;newton-f&lt;/code&gt;, these are the same.
&lt;/p&gt;

&lt;p&gt;
This is just the tip of the iceberg though. You may have noticed that none of the variables in the let* had any descriptions. Sure, you could put some comments after them, but those are not really part of the code.
&lt;/p&gt;

&lt;p&gt;
Also, we had to define the variables in advance of the expression. That is a limitation of how computers work, they cannot evaluate undefined variables. It &lt;i&gt;constrains&lt;/i&gt; how we can express the idea. What if we could instead specify the equation first, then the data? That way we are clear what we are trying to do at a higher level, and fill in the details later. Suppose we wanted a syntax like the block below instead. Here we emphasize the equation we are solving first, and then define the variables and quantities used in the equation, and finally the guess that we use to find the solution.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;
&lt;pre class="src src-emacs-lisp"&gt;(&lt;span style="color: #0000FF;"&gt;solve1&lt;/span&gt;
 (eqn (+ Fa0 (* -1 Fa) (* ra V?)))
 (data ((k 0.1 &lt;span style="color: #008000;"&gt;"rate constant 1/min"&lt;/span&gt;)
        (Ca0 1.0 &lt;span style="color: #008000;"&gt;"feed concentration"&lt;/span&gt;)
        (v0 1 &lt;span style="color: #008000;"&gt;"volumetric flow L/min"&lt;/span&gt;)
        (Fa0 (* v0 Ca0) &lt;span style="color: #008000;"&gt;"Inlet molar flow"&lt;/span&gt;)
        (X 0.5 &lt;span style="color: #008000;"&gt;"Desired conversion"&lt;/span&gt;)
        (Fa (* Fa0 (- 1 X)) &lt;span style="color: #008000;"&gt;"Exit molar flow"&lt;/span&gt;)
        (Ca (/ Fa v0) &lt;span style="color: #008000;"&gt;"exit concentration"&lt;/span&gt;)
        (ra (* -1 k Ca) &lt;span style="color: #008000;"&gt;"rate in the reactor"&lt;/span&gt;)))
 (guess 8))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
That is achievable with the solve1 macro below! It too has some limitations, mostly the order of the data block still has to be correct, e.g. you cannot use a variable before it is defined. It would take some serious macro-fu to sort these so that everything is defined in the right order! Still, it allows you to express an &lt;i&gt;executable&lt;/i&gt; idea in the order we defined. The strings in this syntax for documenting the variables are ignored, but they could be used in the macro to print useful information or something else you could imagine. You could also make them mandatory to encourage documentation.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;
&lt;pre class="src src-emacs-lisp"&gt;(&lt;span style="color: #0000FF;"&gt;defmacro&lt;/span&gt; &lt;span style="color: #006699;"&gt;solve1&lt;/span&gt; (&lt;span style="color: #6434A3;"&gt;&amp;amp;rest&lt;/span&gt; body)
  (&lt;span style="color: #0000FF;"&gt;let&lt;/span&gt; ((expression (second (assoc 'eqn body)))
        (data (&lt;span style="color: #0000FF;"&gt;loop&lt;/span&gt; for d in (second (assoc 'data body))
                    collect (list (first d) (second d))))
        (guess (second (assoc 'guess body))))
    `(&lt;span style="color: #0000FF;"&gt;let*&lt;/span&gt; ,data
       (newton-f
        (&lt;span style="color: #0000FF;"&gt;lambda&lt;/span&gt; ,(&lt;span style="color: #0000FF;"&gt;loop&lt;/span&gt; for item in (-flatten expression)
                       if (&lt;span style="color: #0000FF;"&gt;and&lt;/span&gt; (symbolp item) (s-ends-with? &lt;span style="color: #008000;"&gt;"?"&lt;/span&gt; (symbol-name item)))
                       collect item)
          ,expression)
        ,guess))))
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;
To summarize, lisp macros allow us to rewrite the syntax of code before it is evaluated. This gives us the opportunity to inspect it, and generate new code, e.g. functions with arguments based on the contents of expressions, to save us typing. It also allows us to define ideas in a near arbitrary order that make sense to us, and then rearrange them so they make sense to the computer. See, for example,  &lt;a href="http://kitchingroup.cheme.cmu.edu/blog/2017/03/22/A-better-defun-for-emacs-lisp/"&gt;this post&lt;/a&gt; for an example of changing how functions are defined.
&lt;/p&gt;

&lt;p&gt;
This seems to be heading in the domain specific language direction. I think it would be very helpful in engineering problem solving to build up tools like this. They could start out simple for new students to use. They never need to see the macro parts of this, just to learn how to use them for problem solving. These beginner tools would be limited in what they could do to minimize how much lisp is required to be learned so students can focus on the problem solving. Eventually they might outgrow them, and in the process transition to having the full lisp language at their disposal for problem solving.
&lt;/p&gt;


&lt;div id="outline-container-org18a4554" class="outline-2"&gt;
&lt;h2 id="org18a4554"&gt;&lt;a id="ID-53A5F60F-F929-43BB-AD9D-167D6EBEB8EB"&gt;&lt;/a&gt;&lt;span class="section-number-2"&gt;1&lt;/span&gt; The Newton solver in emacs-lisp&lt;/h2&gt;
&lt;div class="outline-text-2" id="text-1"&gt;
&lt;p&gt;
This is an emacs-lisp implementation of Newton's method. It is a simple implementation for a single variable. The tolerance and step-size are hard-coded for this post because we focus on the partial symbolic solver, not the best solver methods.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;
&lt;pre class="src src-emacs-lisp"&gt;&lt;span style="color: #8D8D84;"&gt;;; &lt;/span&gt;&lt;span style="color: #8D8D84; font-style: italic;"&gt;See https://en.wikipedia.org/wiki/Newton%27s_method for the method&lt;/span&gt;

(&lt;span style="color: #0000FF;"&gt;defun&lt;/span&gt; &lt;span style="color: #006699;"&gt;newton-f&lt;/span&gt; (func x0)
  &lt;span style="color: #036A07;"&gt;"Solve the equation FUNC(x)=0 using Newton's method.&lt;/span&gt;
&lt;span style="color: #036A07;"&gt;X0 is an initial guess."&lt;/span&gt;
  (&lt;span style="color: #0000FF;"&gt;let*&lt;/span&gt; ((tolerance 1e-6)
         (x x0)
         (dx 1e-6)
         fx fpx)
    (&lt;span style="color: #0000FF;"&gt;while&lt;/span&gt; (&amp;gt; (abs (funcall func x)) tolerance)
      (&lt;span style="color: #0000FF;"&gt;setq&lt;/span&gt; fx (funcall func x)
            fpx (/ (- (funcall func (+ x dx)) (funcall func (- x dx))) (* 2 dx))
            x (- x (/ fx fpx))))
    x))
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;Copyright (C) 2017 by John Kitchin. See the &lt;a href="/copying.html"&gt;License&lt;/a&gt; for information about copying.&lt;p&gt;
&lt;p&gt;&lt;a href="/org/2017/05/21/A-partial-symbolic-numeric-solver-in-emacs-lisp.org"&gt;org-mode source&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Org-mode version = 9.0.5&lt;/p&gt;]]></content:encoded>
    </item>
    <item>
      <title>Uncertainty in an integral equation</title>
      <link>https://kitchingroup.cheme.cmu.edu/blog/2013/07/10/Uncertainty-in-an-integral-equation</link>
      <pubDate>Wed, 10 Jul 2013 09:05:02 EDT</pubDate>
      <category><![CDATA[math]]></category>
      <category><![CDATA[uncertainty]]></category>
      <guid isPermaLink="false">-K18eqwvCJAIOIRhVfWk9J0Zf08=</guid>
      <description>Uncertainty in an integral equation</description>
      <content:encoded><![CDATA[



&lt;p&gt;
In a &lt;a href="http://jkitchin.github.io/blog/2013/01/06/Integrating-a-batch-reactor-design-equation/"&gt;previous example&lt;/a&gt;, we solved for the time to reach a specific conversion in a batch reactor. However, it is likely there is uncertainty in the rate constant, and possibly in the initial concentration. Here we examine the effects of that uncertainty on the time to reach the desired conversion.
&lt;/p&gt;

&lt;p&gt;
To do this we have to write a function that takes arguments with uncertainty, and wrap the function with the uncertainties.wrap decorator. The function must return a single float number (current limitation of the uncertainties package). Then, we simply call the function, and the uncertainties from the inputs will be automatically propagated to the outputs. Let us say there is about 10% uncertainty in the rate constant, and 1% uncertainty in the initial concentration.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;from&lt;/span&gt; scipy.integrate &lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; quad
&lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; uncertainties &lt;span style="color: #8b0000;"&gt;as&lt;/span&gt; u

k = u.ufloat((1.0e-3, 1.0e-4))
Ca0 = u.ufloat((1.0, 0.01))&lt;span style="color: #ff0000; font-weight: bold;"&gt;# &lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;mol/L&lt;/span&gt;

@u.wrap
&lt;span style="color: #8b0000;"&gt;def&lt;/span&gt; &lt;span style="color: #8b2323;"&gt;func&lt;/span&gt;(k, Ca0):
    &lt;span style="color: #8b0000;"&gt;def&lt;/span&gt; &lt;span style="color: #8b2323;"&gt;integrand&lt;/span&gt;(X):
        &lt;span style="color: #8b0000;"&gt;return&lt;/span&gt; 1./(k*Ca0)*(1./(1-X)**2)
    integral, abserr = quad(integrand, 0, 0.9)
    &lt;span style="color: #8b0000;"&gt;return&lt;/span&gt; integral

sol = func(k, Ca0)
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; &lt;span style="color: #228b22;"&gt;'t = {0} seconds ({1} hours)'&lt;/span&gt;.format(sol, sol/3600)
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
t = 9000.0+/-904.488801332 seconds (2.5+/-0.251246889259 hours)
&lt;/pre&gt;

&lt;p&gt;
The result shows about a 10% uncertainty in the time, which is similar to the largest uncertainty in the inputs.  This information should certainly be used in making decisions about how long to actually run the reactor to be sure of reaching the goal. For example, in this case, running the reactor for 3 hours (that is roughly + 2&amp;sigma;) would ensure at a high level of confidence (approximately 95% confidence) that you reach at least 90% conversion.  
&lt;/p&gt;
&lt;p&gt;Copyright (C) 2013 by John Kitchin. See the &lt;a href="/copying.html"&gt;License&lt;/a&gt; for information about copying.&lt;p&gt;&lt;p&gt;&lt;a href="/org/2013/07/10/Uncertainty-in-an-integral-equation.org"&gt;org-mode source&lt;/a&gt;&lt;p&gt;]]></content:encoded>
    </item>
    <item>
      <title>Is your ice cream float bigger than mine</title>
      <link>https://kitchingroup.cheme.cmu.edu/blog/2013/05/27/Is-your-ice-cream-float-bigger-than-mine</link>
      <pubDate>Mon, 27 May 2013 07:46:36 EDT</pubDate>
      <category><![CDATA[math]]></category>
      <guid isPermaLink="false">mJdSUXs8-OSXlva3i3HMOzKXVrA=</guid>
      <description>Is your ice cream float bigger than mine</description>
      <content:encoded><![CDATA[



&lt;p&gt;
Float numbers (i.e. the ones with decimals) cannot be perfectly represented in a computer. This can lead to some artifacts when you have to compare float numbers that on paper should be the same, but in silico are not. Let us look at some examples. In this example, we do some simple math that should result in an answer of 1, and then see if the answer is &amp;ldquo;equal&amp;rdquo; to one.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 3.0 * (1.0/3.0)
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 1.0 == 3.0 * (1.0/3.0)
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
1.0
True
&lt;/pre&gt;

&lt;p&gt;
Everything looks fine. Now, consider this example.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 49.0 * (1.0/49.0)
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 1.0 == 49.0 * (1.0/49.0)
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
1.0
False
&lt;/pre&gt;

&lt;p&gt;
The first line looks like everything is find, but the equality fails!
&lt;/p&gt;

&lt;pre class="example"&gt;
1.0
False
&lt;/pre&gt;

&lt;p&gt;
You can see here why the equality statement fails. We will print the two numbers to sixteen decimal places.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; &lt;span style="color: #228b22;"&gt;'{0:1.16f}'&lt;/span&gt;.format(49.0 * (1.0/49.0) )
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; &lt;span style="color: #228b22;"&gt;'{0:1.16f}'&lt;/span&gt;.format(1.0)
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 1 - 49.0 * (1.0/49.0)
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
0.9999999999999999
1.0000000000000000
1.11022302463e-16
&lt;/pre&gt;

&lt;p&gt;
The two numbers actually are not equal to each other because of float math. They are &lt;i&gt;very, very&lt;/i&gt; close to each other, but not the same.
&lt;/p&gt;

&lt;p&gt;
This leads to the idea of asking if two numbers are equal to each other within some tolerance. The question of what tolerance to use requires thought. Should it be an absolute tolerance? a relative tolerance? How large should the tolerance be? We will use the distance between 1 and the nearest floating point number (this is &lt;code&gt;eps&lt;/code&gt; in Matlab). &lt;code&gt;numpy&lt;/code&gt; can tell us this number with the &lt;code&gt;np.spacing&lt;/code&gt; command.
&lt;/p&gt;

&lt;p&gt;
Below, we implement a comparison function from &lt;a href="https://doi.org/10.1107/S010876730302186X" &gt;&lt;a href="10.1107/S010876730302186X" &gt;10.1107/S010876730302186X&lt;/a&gt;&lt;/a&gt; that allows comparisons with tolerance.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;# &lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;Implemented from Acta Crystallographica A60, 1-6 (2003). doi:10.1107/S010876730302186X&lt;/span&gt;

&lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; numpy &lt;span style="color: #8b0000;"&gt;as&lt;/span&gt; np
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; np.spacing(1)

&lt;span style="color: #8b0000;"&gt;def&lt;/span&gt; &lt;span style="color: #8b2323;"&gt;feq&lt;/span&gt;(x, y, epsilon):
    &lt;span style="color: #228b22;"&gt;'x == y'&lt;/span&gt;
    &lt;span style="color: #8b0000;"&gt;return&lt;/span&gt; &lt;span style="color: #8b0000;"&gt;not&lt;/span&gt;((x &amp;lt; (y - epsilon)) &lt;span style="color: #8b0000;"&gt;or&lt;/span&gt; (y &amp;lt; (x - epsilon)))

&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; feq(1.0, 49.0 * (1.0/49.0), np.spacing(1))
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
2.22044604925e-16
True
&lt;/pre&gt;

&lt;p&gt;
For completeness, here are the other float comparison operators from that paper. We also show a few examples.
&lt;/p&gt;
&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; numpy &lt;span style="color: #8b0000;"&gt;as&lt;/span&gt; np

&lt;span style="color: #8b0000;"&gt;def&lt;/span&gt; &lt;span style="color: #8b2323;"&gt;flt&lt;/span&gt;(x, y, epsilon):
    &lt;span style="color: #228b22;"&gt;'x &amp;lt; y'&lt;/span&gt;
    &lt;span style="color: #8b0000;"&gt;return&lt;/span&gt; x &amp;lt; (y - epsilon)

&lt;span style="color: #8b0000;"&gt;def&lt;/span&gt; &lt;span style="color: #8b2323;"&gt;fgt&lt;/span&gt;(x, y, epsilon):
    &lt;span style="color: #228b22;"&gt;'x &amp;gt; y'&lt;/span&gt;
    &lt;span style="color: #8b0000;"&gt;return&lt;/span&gt; y &amp;lt; (x - epsilon)

&lt;span style="color: #8b0000;"&gt;def&lt;/span&gt; &lt;span style="color: #8b2323;"&gt;fle&lt;/span&gt;(x, y, epsilon):
    &lt;span style="color: #228b22;"&gt;'x &amp;lt;= y'&lt;/span&gt;
    &lt;span style="color: #8b0000;"&gt;return&lt;/span&gt; &lt;span style="color: #8b0000;"&gt;not&lt;/span&gt;(y &amp;lt; (x - epsilon))

&lt;span style="color: #8b0000;"&gt;def&lt;/span&gt; &lt;span style="color: #8b2323;"&gt;fge&lt;/span&gt;(x, y, epsilon):
    &lt;span style="color: #228b22;"&gt;'x &amp;gt;= y'&lt;/span&gt;
    &lt;span style="color: #8b0000;"&gt;return&lt;/span&gt; &lt;span style="color: #8b0000;"&gt;not&lt;/span&gt;(x &amp;lt; (y - epsilon))

&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; fge(1.0, 49.0 * (1.0/49.0), np.spacing(1))
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; fle(1.0, 49.0 * (1.0/49.0), np.spacing(1))

&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; fgt(1.0 + np.spacing(1), 49.0 * (1.0/49.0), np.spacing(1))
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; flt(1.0 - 2 * np.spacing(1), 49.0 * (1.0/49.0), np.spacing(1))
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
True
True
True
True
&lt;/pre&gt;

&lt;p&gt;
As you can see, float comparisons can be tricky. You have to give a lot of thought to how to make the comparisons, and the functions shown above are not the only way to do it. You need to build in testing to make sure your comparisons are doing what you want.
&lt;/p&gt;
&lt;p&gt;Copyright (C) 2013 by John Kitchin. See the &lt;a href="/copying.html"&gt;License&lt;/a&gt; for information about copying.&lt;p&gt;&lt;p&gt;&lt;a href="/org/2013/05/27/Is-your-ice-cream-float-bigger-than-mine.org"&gt;org-mode source&lt;/a&gt;&lt;p&gt;
]]></content:encoded>
    </item>
    <item>
      <title>Numerical Simpsons rule</title>
      <link>https://kitchingroup.cheme.cmu.edu/blog/2013/03/08/Numerical-Simpsons-rule</link>
      <pubDate>Fri, 08 Mar 2013 18:18:55 EST</pubDate>
      <category><![CDATA[math]]></category>
      <category><![CDATA[integration]]></category>
      <guid isPermaLink="false">vmtnHrNkUcTa2PmQCOP7XnVGrO0=</guid>
      <description>Numerical Simpsons rule</description>
      <content:encoded><![CDATA[


&lt;p&gt;

A more accurate numerical integration than the trapezoid method is &lt;a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.simps.html" &gt;Simpson's rule&lt;/a&gt;. The syntax is similar to trapz, but the method is in scipy.integrate.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; numpy &lt;span style="color: #8b0000;"&gt;as&lt;/span&gt; np
&lt;span style="color: #8b0000;"&gt;from&lt;/span&gt; scipy.integrate &lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; simps, romb

a = 0.0; b = np.pi / 4.0;
N = 10  &lt;span style="color: #ff0000; font-weight: bold;"&gt;# this is the number of intervals&lt;/span&gt;

x = np.linspace(a, b, N)
y = np.cos(x)

t = np.trapz(y, x)
s = simps(y, x)
a = np.sin(b) - np.sin(a)

&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt;
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; &lt;span style="color: #228b22;"&gt;'trapz = {0} ({1:%} error)'&lt;/span&gt;.format(t, (t - a)/a)
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; &lt;span style="color: #228b22;"&gt;'simps = {0} ({1:%} error)'&lt;/span&gt;.format(s, (s - a)/a)
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; &lt;span style="color: #228b22;"&gt;'analy = {0}'&lt;/span&gt;.format(a)
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
&amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt;
trapz = 0.70665798038 (-0.063470% error)
simps = 0.707058914216 (-0.006769% error)
analy = 0.707106781187
&lt;/pre&gt;

&lt;p&gt;
You can see the Simpson's method is more accurate than the trapezoid method.
&lt;/p&gt;
&lt;p&gt;Copyright (C) 2013 by John Kitchin. See the &lt;a href="/copying.html"&gt;License&lt;/a&gt; for information about copying.&lt;p&gt;&lt;p&gt;&lt;a href="/org/2013/03/08/Numerical-Simpsons-rule.org"&gt;org-mode source&lt;/a&gt;&lt;p&gt;]]></content:encoded>
    </item>
    <item>
      <title>Symbolic math in python</title>
      <link>https://kitchingroup.cheme.cmu.edu/blog/2013/03/01/Symbolic-math-in-python</link>
      <pubDate>Fri, 01 Mar 2013 19:07:48 EST</pubDate>
      <category><![CDATA[symbolic]]></category>
      <category><![CDATA[math]]></category>
      <guid isPermaLink="false">AAKSB0VVX_XkVXNAmXvGC1HyE4w=</guid>
      <description>Symbolic math in python</description>
      <content:encoded><![CDATA[


&lt;p&gt;
 &lt;a href="http://matlab.cheme.cmu.edu/2011/08/10/symbolic-math-in-matlab/" &gt;Matlab post&lt;/a&gt;
Python has capability to do symbolic math through the sympy package. 
&lt;/p&gt;
&lt;div id="outline-container-1" class="outline-2"&gt;
&lt;h2 id="sec-1"&gt;&lt;span class="section-number-2"&gt;1&lt;/span&gt; Solve the quadratic equation&lt;/h2&gt;
&lt;div class="outline-text-2" id="text-1"&gt;
&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;from&lt;/span&gt; sympy &lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; solve, symbols, pprint

a,b,c,x = symbols(&lt;span style="color: #228b22;"&gt;'a,b,c,x'&lt;/span&gt;)

f = a*x**2 + b*x + c

solution = solve(f, x)
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; solution
pprint(solution)
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
&amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; [(-b + (-4*a*c + b**2)**(1/2))/(2*a), -(b + (-4*a*c + b**2)**(1/2))/(2*a)]
_____________   /       _____________\ 
        /           2    |      /           2 | 
 -b + \/  -4*a*c + b    -\b + \/  -4*a*c + b  / 
[---------------------, -----------------------]
          2*a                     2*a
&lt;/pre&gt;

&lt;p&gt;
The solution you should recognize in the form of \(\frac{b \pm \sqrt{b^2 - 4 a c}}{2 a}\) although python does not print it this nicely!
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id="outline-container-2" class="outline-2"&gt;
&lt;h2 id="sec-2"&gt;&lt;span class="section-number-2"&gt;2&lt;/span&gt; differentiation&lt;/h2&gt;
&lt;div class="outline-text-2" id="text-2"&gt;
&lt;p&gt;
you might find this helpful!
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;from&lt;/span&gt; sympy &lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; diff

&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; diff(f, x)
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; diff(f, x, 2)

&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; diff(f, a)
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
&amp;gt;&amp;gt;&amp;gt; 2*a*x + b
2*a
&amp;gt;&amp;gt;&amp;gt; x**2
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id="outline-container-3" class="outline-2"&gt;
&lt;h2 id="sec-3"&gt;&lt;span class="section-number-2"&gt;3&lt;/span&gt; integration&lt;/h2&gt;
&lt;div class="outline-text-2" id="text-3"&gt;
&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;from&lt;/span&gt; sympy &lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; integrate

&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; integrate(f, x)          &lt;span style="color: #ff0000; font-weight: bold;"&gt;# &lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;indefinite integral&lt;/span&gt;
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; integrate(f, (x, 0, 1))  &lt;span style="color: #ff0000; font-weight: bold;"&gt;# &lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;definite integral from x=0..1&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
&amp;gt;&amp;gt;&amp;gt; a*x**3/3 + b*x**2/2 + c*x
a/3 + b/2 + c
&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id="outline-container-4" class="outline-2"&gt;
&lt;h2 id="sec-4"&gt;&lt;span class="section-number-2"&gt;4&lt;/span&gt; Analytically solve a simple ODE&lt;/h2&gt;
&lt;div class="outline-text-2" id="text-4"&gt;
&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;from&lt;/span&gt; sympy &lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; Function, Symbol, dsolve
f = Function(&lt;span style="color: #228b22;"&gt;'f'&lt;/span&gt;)
x = Symbol(&lt;span style="color: #228b22;"&gt;'x'&lt;/span&gt;)
fprime = f(x).diff(x) - f(x) &lt;span style="color: #ff0000; font-weight: bold;"&gt;# &lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;f' = f(x)&lt;/span&gt;

y = dsolve(fprime, f(x))

&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; y
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; y.subs(x,4)
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; [y.subs(x, X) &lt;span style="color: #8b0000;"&gt;for&lt;/span&gt; X &lt;span style="color: #8b0000;"&gt;in&lt;/span&gt; [0, 0.5, 1]] &lt;span style="color: #ff0000; font-weight: bold;"&gt;# &lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;multiple values&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
&amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; f(x) == exp(C1 + x)
f(4) == exp(C1 + 4)
[f(0) == exp(C1), f(0.5) == exp(C1 + 0.5), f(1) == exp(C1 + 1)]
&lt;/pre&gt;

&lt;p&gt;
It is not clear you can solve the initial value problem to get C1.
&lt;/p&gt;

&lt;p&gt;
The symbolic math in sympy is pretty good. It is not up to the capability of Maple or Mathematica, (but neither is Matlab) but it continues to be developed, and could be helpful in some situations.
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;p&gt;Copyright (C) 2013 by John Kitchin. See the &lt;a href="/copying.html"&gt;License&lt;/a&gt; for information about copying.&lt;p&gt;&lt;p&gt;&lt;a href="/org/2013/03/01/Symbolic-math-in-python.org"&gt;org-mode source&lt;/a&gt;&lt;p&gt;]]></content:encoded>
    </item>
    <item>
      <title>Smooth transitions between two constants</title>
      <link>https://kitchingroup.cheme.cmu.edu/blog/2013/02/27/Smooth-transitions-between-two-constants</link>
      <pubDate>Wed, 27 Feb 2013 14:53:22 EST</pubDate>
      <category><![CDATA[math]]></category>
      <guid isPermaLink="false">vWwKTqPk3pQJqNPay-KZnZm1Ym4=</guid>
      <description>Smooth transitions between two constants</description>
      <content:encoded><![CDATA[


&lt;p&gt;
Suppose we have a parameter that has two different values depending on the value of a dimensionless number. For example when the dimensionless number is much less than 1, x = 2/3, and when x is much greater than 1, x = 1. We desire a smooth transition from 2/3 to 1  as a function of x to avoid discontinuities in functions of x. We will adapt the smooth transitions between functions to be a smooth transition between constants.
&lt;/p&gt;

&lt;p&gt;
We define our function as \(x(D) = x0 + (x1 - x0)*(1 - sigma(D,w)\). We control the rate of the transition by the variable \(w\)
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; numpy &lt;span style="color: #8b0000;"&gt;as&lt;/span&gt; np
&lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; matplotlib.pyplot &lt;span style="color: #8b0000;"&gt;as&lt;/span&gt; plt

x0 = 2.0 / 3.0
x1 = 1.5

w = 0.05

D = np.linspace(0,2, 500)

sigmaD = 1.0 / (1.0 + np.exp(-(1 - D) / w))

x =  x0 + (x1 - x0)*(1 - sigmaD)

plt.plot(D, x)
plt.xlabel(&lt;span style="color: #228b22;"&gt;'D'&lt;/span&gt;); plt.ylabel(&lt;span style="color: #228b22;"&gt;'x'&lt;/span&gt;)
plt.savefig(&lt;span style="color: #228b22;"&gt;'images/smooth-transitions-constants.png'&lt;/span&gt;)
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src="/img/./images/smooth-transitions-constants.png"&gt;&lt;p&gt;

&lt;p&gt;
This is a nice trick to get an analytical function with continuous derivatives for a transition between two constants. You could have the transition occur at a value other than D = 1, as well by changing the argument to the exponential function.
&lt;/p&gt;
&lt;p&gt;Copyright (C) 2013 by John Kitchin. See the &lt;a href="/copying.html"&gt;License&lt;/a&gt; for information about copying.&lt;p&gt;&lt;p&gt;&lt;a href="/org/2013/02/27/Smooth-transitions-between-two-constants.org"&gt;org-mode source&lt;/a&gt;&lt;p&gt;]]></content:encoded>
    </item>
    <item>
      <title>A novel way to numerically estimate the derivative of a function - complex-step derivative approximation</title>
      <link>https://kitchingroup.cheme.cmu.edu/blog/2013/02/27/A-novel-way-to-numerically-estimate-the-derivative-of-a-function-complex-step-derivative-approximation</link>
      <pubDate>Wed, 27 Feb 2013 14:51:38 EST</pubDate>
      <category><![CDATA[math]]></category>
      <guid isPermaLink="false">fZoaOX-4OHxBQp8RZo8Bd7BaRRo=</guid>
      <description>A novel way to numerically estimate the derivative of a function - complex-step derivative approximation</description>
      <content:encoded><![CDATA[


&lt;p&gt;

&lt;/p&gt;

&lt;p&gt;
&lt;a href="http://matlab.cheme.cmu.edu/2011/12/24/a-novel-way-to-numerically-estimate-the-derivative-of-a-function-complex-step-derivative-approximation/"&gt;Matlab post&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
Adapted from &lt;a href="http://biomedicalcomputationreview.org/2/3/8.pdf"&gt;http://biomedicalcomputationreview.org/2/3/8.pdf&lt;/a&gt; and
&lt;a href="http://dl.acm.org/citation.cfm?id=838250.838251"&gt;http://dl.acm.org/citation.cfm?id=838250.838251&lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
This posts introduces a novel way to numerically estimate the derivative
of a function that does not involve finite difference schemes. Finite
difference schemes are approximations to derivatives that become more and
more accurate as the step size goes to zero, except that as the step size
approaches the limits of machine accuracy, new errors can appear in the
approximated results. In the references above, a new way to compute the
derivative is presented that does not rely on differences!
&lt;/p&gt;

&lt;p&gt;
The new way is: \(f'(x) = \rm{imag}(f(x + i\Delta x)/\Delta x)\) where the
function \(f\) is evaluated in imaginary space with a small \(\Delta x\) in
the complex plane. The derivative is miraculously equal to the imaginary
part of the result in the limit of \(\Delta x \rightarrow 0\)!
&lt;/p&gt;

&lt;p&gt;
This example comes from the first link. The derivative must be evaluated
using the chain rule.  We compare a forward difference, central
difference and complex-step derivative approximations.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; numpy &lt;span style="color: #8b0000;"&gt;as&lt;/span&gt; np
&lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; matplotlib.pyplot &lt;span style="color: #8b0000;"&gt;as&lt;/span&gt; plt

&lt;span style="color: #8b0000;"&gt;def&lt;/span&gt; &lt;span style="color: #8b2323;"&gt;f&lt;/span&gt;(x):   &lt;span style="color: #8b0000;"&gt;return&lt;/span&gt; np.sin(3*x)*np.log(x)

x = 0.7
h = 1e-7

&lt;span style="color: #ff0000; font-weight: bold;"&gt;# &lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;analytical derivative&lt;/span&gt;
dfdx_a = 3 * np.cos( 3*x)*np.log(x) + np.sin(3*x) / x

&lt;span style="color: #ff0000; font-weight: bold;"&gt;# &lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;finite difference&lt;/span&gt;
dfdx_fd = (f(x + h) - f(x))/h

&lt;span style="color: #ff0000; font-weight: bold;"&gt;# &lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;central difference&lt;/span&gt;
dfdx_cd = (f(x+h)-f(x-h))/(2*h)

&lt;span style="color: #ff0000; font-weight: bold;"&gt;# &lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;complex method&lt;/span&gt;
dfdx_I = np.imag(f(x + np.complex(0, h))/h)

&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; dfdx_a
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; dfdx_fd
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; dfdx_cd
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; dfdx_cd
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
1.77335410624
1.7733539398
1.77335410523
1.77335410523
&lt;/pre&gt;

&lt;p&gt;
These are all the same to 4 decimal places. The simple finite difference is the least accurate, and the central differences is practically the same as the complex number approach.
&lt;/p&gt;

&lt;p&gt;
Let us use this method to verify the fundamental Theorem of Calculus, i.e.
to evaluate the derivative of an integral function. Let \(f(x) =
\int\limits_1^{x^2} tan(t^3)dt\), and we now want to compute df/dx.
Of course, this can be done
&lt;a href="http://mathmistakes.info/facts/CalculusFacts/learn/doi/doif.html"&gt;analytically&lt;/a&gt;, but it is not trivial!
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; numpy &lt;span style="color: #8b0000;"&gt;as&lt;/span&gt; np
&lt;span style="color: #8b0000;"&gt;from&lt;/span&gt; scipy.integrate &lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; quad

&lt;span style="color: #8b0000;"&gt;def&lt;/span&gt; &lt;span style="color: #8b2323;"&gt;f_&lt;/span&gt;(z):
    &lt;span style="color: #8b0000;"&gt;def&lt;/span&gt; &lt;span style="color: #8b2323;"&gt;integrand&lt;/span&gt;(t):
        &lt;span style="color: #8b0000;"&gt;return&lt;/span&gt; np.tan(t**3)
    &lt;span style="color: #8b0000;"&gt;return&lt;/span&gt; quad(integrand, 0, z**2)

f = np.vectorize(f_)

x = np.linspace(0, 1)

h = 1e-7

dfdx = np.imag(f(x + &lt;span style="color: #8b0000;"&gt;complex&lt;/span&gt;(0, h)))/h
dfdx_analytical = 2 * x * np.tan(x**6)

&lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; matplotlib.pyplot &lt;span style="color: #8b0000;"&gt;as&lt;/span&gt; plt

plt.plot(x, dfdx, x, dfdx_analytical, &lt;span style="color: #228b22;"&gt;'r--'&lt;/span&gt;)
plt.show()
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
&amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; ... ... ... ... &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; c:\Python27\lib\site-packages\scipy\integrate\quadpack.py:312: ComplexWarning: Casting complex values to real discards the imaginary part
  return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in &amp;lt;module&amp;gt;
  File "c:\Python27\lib\site-packages\numpy\lib\function_base.py", line 1885, in __call__
    for x, c in zip(self.ufunc(*newargs), self.otypes)])
  File "&amp;lt;stdin&amp;gt;", line 4, in f_
  File "c:\Python27\lib\site-packages\scipy\integrate\quadpack.py", line 247, in quad
    retval = _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points)
  File "c:\Python27\lib\site-packages\scipy\integrate\quadpack.py", line 312, in _quad
    return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
TypeError: can't convert complex to float
&amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; &amp;gt;&amp;gt;&amp;gt; Traceback (most recent call last):
  File "&amp;lt;stdin&amp;gt;", line 1, in &amp;lt;module&amp;gt;
NameError: name 'dfdx' is not defined
&lt;/pre&gt;

&lt;p&gt;
Interesting this fails.&lt;/p&gt;
&lt;p&gt;Copyright (C) 2013 by John Kitchin. See the &lt;a href="/copying.html"&gt;License&lt;/a&gt; for information about copying.&lt;p&gt;&lt;p&gt;&lt;a href="/org/2013/02/27/A-novel-way-to-numerically-estimate-the-derivative-of-a-function---complex-step-derivative-approximation.org"&gt;org-mode source&lt;/a&gt;&lt;p&gt;]]></content:encoded>
    </item>
    <item>
      <title>Vectorized numeric derivatives</title>
      <link>https://kitchingroup.cheme.cmu.edu/blog/2013/02/27/Vectorized-numeric-derivatives</link>
      <pubDate>Wed, 27 Feb 2013 14:51:11 EST</pubDate>
      <category><![CDATA[math]]></category>
      <guid isPermaLink="false">jx4qLZXrfoB1s6_FeETq-arjSZ8=</guid>
      <description>Vectorized numeric derivatives</description>
      <content:encoded><![CDATA[


&lt;p&gt;

Loops are usually not great for performance. Numpy offers some vectorized methods that allow us to compute derivatives without loops, although this comes at the mental cost of harder to understand syntax
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; numpy &lt;span style="color: #8b0000;"&gt;as&lt;/span&gt; np
&lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; matplotlib.pyplot &lt;span style="color: #8b0000;"&gt;as&lt;/span&gt; plt

x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
dy_analytical = np.cos(x)


&lt;span style="color: #ff0000; font-weight: bold;"&gt;# &lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;we need to specify the size of dy ahead because diff returns&lt;/span&gt;
&lt;span style="color: #ff0000; font-weight: bold;"&gt;#&lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;an array of n-1 elements&lt;/span&gt;
dy = np.zeros(y.shape, np.float) &lt;span style="color: #ff0000; font-weight: bold;"&gt;#&lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;we know it will be this size&lt;/span&gt;
dy[0:-1] = np.diff(y) / np.diff(x)
dy[-1] = (y[-1] - y[-2]) / (x[-1] - x[-2])


&lt;span style="color: #228b22;"&gt;'''&lt;/span&gt;
&lt;span style="color: #228b22;"&gt;calculate dy by center differencing using array slices&lt;/span&gt;
&lt;span style="color: #228b22;"&gt;'''&lt;/span&gt;

dy2 = np.zeros(y.shape,np.float) &lt;span style="color: #ff0000; font-weight: bold;"&gt;#&lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;we know it will be this size&lt;/span&gt;
dy2[1:-1] = (y[2:] - y[0:-2]) / (x[2:] - x[0:-2])

&lt;span style="color: #ff0000; font-weight: bold;"&gt;# &lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;now the end points&lt;/span&gt;
dy2[0] = (y[1] - y[0]) / (x[1] - x[0])
dy2[-1] = (y[-1] - y[-2]) / (x[-1] - x[-2])

plt.plot(x,y)
plt.plot(x,dy_analytical,label=&lt;span style="color: #228b22;"&gt;'analytical derivative'&lt;/span&gt;)
plt.plot(x,dy,label=&lt;span style="color: #228b22;"&gt;'forward diff'&lt;/span&gt;)
plt.plot(x,dy2,&lt;span style="color: #228b22;"&gt;'k--'&lt;/span&gt;,lw=2,label=&lt;span style="color: #228b22;"&gt;'centered diff'&lt;/span&gt;)
plt.legend(loc=&lt;span style="color: #228b22;"&gt;'lower left'&lt;/span&gt;)
plt.savefig(&lt;span style="color: #228b22;"&gt;'images/vectorized-diffs.png'&lt;/span&gt;)
plt.show()
&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;&lt;img src="/img/./images/vectorized-diffs.png"&gt;&lt;p&gt;
&lt;p&gt;Copyright (C) 2013 by John Kitchin. See the &lt;a href="/copying.html"&gt;License&lt;/a&gt; for information about copying.&lt;p&gt;&lt;p&gt;&lt;a href="/org/2013/02/27/Vectorized-numeric-derivatives.org"&gt;org-mode source&lt;/a&gt;&lt;p&gt;]]></content:encoded>
    </item>
    <item>
      <title>Numeric derivatives by differences</title>
      <link>https://kitchingroup.cheme.cmu.edu/blog/2013/02/27/Numeric-derivatives-by-differences</link>
      <pubDate>Wed, 27 Feb 2013 14:51:06 EST</pubDate>
      <category><![CDATA[math]]></category>
      <guid isPermaLink="false">i3BDtB2lbbG7mdWeeq9M1q7o_Ag=</guid>
      <description>Numeric derivatives by differences</description>
      <content:encoded><![CDATA[


&lt;p&gt;




numpy has a function called numpy.diff() that is similar to the one found in matlab. It calculates the differences between the elements in your list, and returns a list that is one element shorter, which makes it unsuitable for plotting the derivative of a function.
&lt;/p&gt;

&lt;p&gt;
Loops in python are pretty slow (relatively speaking) but they are usually trivial to understand. In this script we show some simple ways to construct derivative vectors using loops. It is implied in these formulas that the data points are equally spaced. If they are not evenly spaced, you need a different approach.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; numpy &lt;span style="color: #8b0000;"&gt;as&lt;/span&gt; np
&lt;span style="color: #8b0000;"&gt;from&lt;/span&gt; pylab &lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; *
&lt;span style="color: #8b0000;"&gt;import&lt;/span&gt; time

&lt;span style="color: #228b22;"&gt;'''&lt;/span&gt;
&lt;span style="color: #228b22;"&gt;These are the brainless way to calculate numerical derivatives. They&lt;/span&gt;
&lt;span style="color: #228b22;"&gt;work well for very smooth data. they are surprisingly fast even up to&lt;/span&gt;
&lt;span style="color: #228b22;"&gt;10000 points in the vector.&lt;/span&gt;
&lt;span style="color: #228b22;"&gt;'''&lt;/span&gt;

x = np.linspace(0.78,0.79,100)
y = np.sin(x)
dy_analytical = np.cos(x)
&lt;span style="color: #228b22;"&gt;'''&lt;/span&gt;
&lt;span style="color: #228b22;"&gt;lets use a forward difference method:&lt;/span&gt;
&lt;span style="color: #228b22;"&gt;that works up until the last point, where there is not&lt;/span&gt;
&lt;span style="color: #228b22;"&gt;a forward difference to use. there, we use a backward difference.&lt;/span&gt;
&lt;span style="color: #228b22;"&gt;'''&lt;/span&gt;

tf1 = time.time()
dyf = [0.0]*&lt;span style="color: #8b0000;"&gt;len&lt;/span&gt;(x)
&lt;span style="color: #8b0000;"&gt;for&lt;/span&gt; i &lt;span style="color: #8b0000;"&gt;in&lt;/span&gt; &lt;span style="color: #8b0000;"&gt;range&lt;/span&gt;(len(y)-1):
    dyf[i] = (y[i+1] - y[i])/(x[i+1]-x[i])
&lt;span style="color: #ff0000; font-weight: bold;"&gt;#&lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;set last element by backwards difference&lt;/span&gt;
dyf[-1] = (y[-1] - y[-2])/(x[-1] - x[-2])

&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; &lt;span style="color: #228b22;"&gt;' Forward difference took %1.1f seconds'&lt;/span&gt; % (time.time() - tf1)

&lt;span style="color: #228b22;"&gt;'''and now a backwards difference'''&lt;/span&gt;
tb1 = time.time()
dyb = [0.0]*&lt;span style="color: #8b0000;"&gt;len&lt;/span&gt;(x)
&lt;span style="color: #ff0000; font-weight: bold;"&gt;#&lt;/span&gt;&lt;span style="color: #ff0000; font-weight: bold;"&gt;set first element by forward difference&lt;/span&gt;
dyb[0] = (y[0] - y[1])/(x[0] - x[1])
&lt;span style="color: #8b0000;"&gt;for&lt;/span&gt; i &lt;span style="color: #8b0000;"&gt;in&lt;/span&gt; &lt;span style="color: #8b0000;"&gt;range&lt;/span&gt;(1,&lt;span style="color: #8b0000;"&gt;len&lt;/span&gt;(y)):
    dyb[i] = (y[i] - y[i-1])/(x[i]-x[i-1])

&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; &lt;span style="color: #228b22;"&gt;' Backward difference took %1.1f seconds'&lt;/span&gt; % (time.time() - tb1)

&lt;span style="color: #228b22;"&gt;'''and now, a centered formula'''&lt;/span&gt;
tc1 = time.time()
dyc = [0.0]*&lt;span style="color: #8b0000;"&gt;len&lt;/span&gt;(x)
dyc[0] = (y[0] - y[1])/(x[0] - x[1])
&lt;span style="color: #8b0000;"&gt;for&lt;/span&gt; i &lt;span style="color: #8b0000;"&gt;in&lt;/span&gt; &lt;span style="color: #8b0000;"&gt;range&lt;/span&gt;(1,&lt;span style="color: #8b0000;"&gt;len&lt;/span&gt;(y)-1):
    dyc[i] = (y[i+1] - y[i-1])/(x[i+1]-x[i-1])
dyc[-1] = (y[-1] - y[-2])/(x[-1] - x[-2])

&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; &lt;span style="color: #228b22;"&gt;' Centered difference took %1.1f seconds'&lt;/span&gt; % (time.time() - tc1)

&lt;span style="color: #228b22;"&gt;'''&lt;/span&gt;
&lt;span style="color: #228b22;"&gt;the centered formula is the most accurate formula here&lt;/span&gt;
&lt;span style="color: #228b22;"&gt;'''&lt;/span&gt;

plt.plot(x,dy_analytical,label=&lt;span style="color: #228b22;"&gt;'analytical derivative'&lt;/span&gt;)
plt.plot(x,dyf,&lt;span style="color: #228b22;"&gt;'--'&lt;/span&gt;,label=&lt;span style="color: #228b22;"&gt;'forward'&lt;/span&gt;)
plt.plot(x,dyb,&lt;span style="color: #228b22;"&gt;'--'&lt;/span&gt;,label=&lt;span style="color: #228b22;"&gt;'backward'&lt;/span&gt;)
plt.plot(x,dyc,&lt;span style="color: #228b22;"&gt;'--'&lt;/span&gt;,label=&lt;span style="color: #228b22;"&gt;'centered'&lt;/span&gt;)

plt.legend(loc=&lt;span style="color: #228b22;"&gt;'lower left'&lt;/span&gt;)
plt.savefig(&lt;span style="color: #228b22;"&gt;'images/simple-diffs.png'&lt;/span&gt;)
plt.show()
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
Forward difference took 0.0 seconds
Backward difference took 0.0 seconds
Centered difference took 0.0 seconds
&lt;/pre&gt;

&lt;p&gt;&lt;img src="/img/./images/simple-diffs.png"&gt;&lt;p&gt;
&lt;p&gt;Copyright (C) 2013 by John Kitchin. See the &lt;a href="/copying.html"&gt;License&lt;/a&gt; for information about copying.&lt;p&gt;&lt;p&gt;&lt;a href="/org/2013/02/27/Numeric-derivatives-by-differences.org"&gt;org-mode source&lt;/a&gt;&lt;p&gt;]]></content:encoded>
    </item>
    <item>
      <title>Basic math</title>
      <link>https://kitchingroup.cheme.cmu.edu/blog/2013/02/27/Basic-math</link>
      <pubDate>Wed, 27 Feb 2013 07:35:24 EST</pubDate>
      <category><![CDATA[math]]></category>
      <category><![CDATA[python]]></category>
      <guid isPermaLink="false">d7TWrAsoJF-1nKn9KnXjrqox9_Y=</guid>
      <description>Basic math</description>
      <content:encoded><![CDATA[


&lt;p&gt;
Python is a basic calculator out of the box. Here we consider the most basic mathematical operations: addition, subtraction, multiplication, division and exponenetiation. we use the to get the output. For now we consider integers and float numbers. An integer is a plain number like 0, 10 or -2345. A float number has a decimal in it. The following are all floats: 1.0, -9., and 3.56. Note the trailing zero is not required, although it is good style.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 2 + 4
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 8.1 - 5
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
6
3.1
&lt;/pre&gt;

&lt;p&gt;
Multiplication is equally straightforward.
&lt;/p&gt;
&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 5 * 4
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 3.1*2
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
20
6.2
&lt;/pre&gt;

&lt;p&gt;
Division is almost as straightforward, but we have to remember that integer division is not the same as float division. Let us consider float division first.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 4.0 / 2.0
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 1.0/3.1
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
2.0
0.322580645161
&lt;/pre&gt;

&lt;p&gt;
Now, consider the integer versions:
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 4 / 2
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 1/3
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
2
0
&lt;/pre&gt;

&lt;p&gt;
The first result is probably what you expected, but the second may come as a surprise. In integer division the remainder is discarded, and the result is an integer. 
&lt;/p&gt;

&lt;p&gt;
Exponentiation is also a basic math operation that python supports directly.
&lt;/p&gt;

&lt;div class="org-src-container"&gt;

&lt;pre class="src src-python"&gt;&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 3.**2
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 3**2
&lt;span style="color: #8b0000;"&gt;print&lt;/span&gt; 2**0.5
&lt;/pre&gt;
&lt;/div&gt;

&lt;pre class="example"&gt;
9.0
9
1.41421356237
&lt;/pre&gt;

&lt;p&gt;
Other types of mathematical operations require us to import functionality from python libraries. We consider those in the next section.
&lt;/p&gt;
&lt;p&gt;Copyright (C) 2013 by John Kitchin. See the &lt;a href="/copying.html"&gt;License&lt;/a&gt; for information about copying.&lt;p&gt;&lt;p&gt;&lt;a href="/org/2013/02/27/Basic-math.org"&gt;org-mode source&lt;/a&gt;&lt;p&gt;]]></content:encoded>
    </item>
  </channel>
</rss>
