Skip to content

Instantly share code, notes, and snippets.

@rickwierenga
Last active October 3, 2021 12:57
Show Gist options
  • Save rickwierenga/ae8734513497c2430ec1220646fea674 to your computer and use it in GitHub Desktop.
Save rickwierenga/ae8734513497c2430ec1220646fea674 to your computer and use it in GitHub Desktop.
We had to approximate the root of x^3+3x-2 for calc1 on an interval of size 1/8, I wrote this program to find it on an interval of size 1/(2^10000). It only takes a few minutes to run.
def gcd(x: int, y: int):
while(y):
x, y = y, x % y
return x
def frac(a: int, b: int):
return '\\seqsplit{' + str(a//gcd(a, b)) + '\\div' + str(b//gcd(a,b)) + '}'
def func(a, n):
""" x=a/2**n, f(x) = x^3+3x-2 """
p1, q1 = a**3, 1 << (3*n) # first coefficient
p2, q2 = 3 * a, 1 << n # second coefficient
den = (q1 * q2)
num = (p1 * q2 + p2 * q1 - 2 * den)
return frac(num, den), (den < 0 or num < 0) and not (den < 0 and num < 0)
# start with 1 / 2**1 = 1/2
a, n = 1, 1
for i in range(10000):
res, neg = func(a, n)
print(f'Neem het midden van ${frac(a-1, 1 << n)}$ en ${frac(a+1, 1 << n)}$. Dat is ${frac(a, 1 << n)}$. $f({frac(a, 1 << n)})={res}{"<" if neg else ">"}0$. \par')
n += 1
a = a*2 + (1 if neg else -1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment