1 min read

Testing a blog post with Python

These posts are written in Blogdown using Rstudio, which makes it possible to write R code and have it evaluated. It would be neat if it was also possible to have calculations made using Python create output in the same format. Apparently, that should be possible with the reticulate package.

An attempt: a piece of code from the Python Workshop last spring:

def find_root(f, lower, upper, eps=1e-6):
    assert sign(f(lower)) != sign(f(upper)), "No guarantee of solution in this interval!"
    l, u = lower, upper
    while ( abs( f(u) - f(l) ) > eps):
        midpoint = (l+u)/2
        y = f(midpoint)
        if sign(y)==sign(f(l)):
            l = midpoint
        else:
            u = midpoint
        # print(l, u, y)
    return midpoint, (l, u)
def sign(x):
    if x<0.0:
        return -1
    else:
        return 1

If it works, it should be possible to find solutions to nonlinear equation, such as \[ e^{2x} = 4.\]

import math
def test_function(x):
  return math.exp(2*x)-4
solution, bounds = find_root(test_function, 0, 1)
print(f"The estimated solution is x={solution}, and x must be in the interval {bounds}.")
## The estimated solution is x=0.6931470632553101, and x must be in the interval (0.6931470632553101, 0.6931471824645996).