Computational-Analysis/chapter-03/ratseq/main.py
Jan-Niclas Loosen 719f5816e9 init repo
2025-05-07 10:48:37 +02:00

66 lines
1.5 KiB
Python

from gmpy2 import mpq # rationale Zahlen
from binseq import REAL as REAL_bs
from ratseq import REAL as REAL_ra
def ra_oneThird(p):
return mpq(1, 3)
x = REAL_ra(ra_oneThird)
print("x: " + x.asString(-50))
# Theorem 3.1 (3)
# Es gibt eine berechenbare Intervallschachtelung von Intervallen mit rationalen Endpunkten, die gegen x konvergiert
# d.h. es gibt berechen-
# bare Folgen (an)n∈N und (bn)n∈N
class REAL_ra_from_bs(REAL_ra): # Subklasse
def __init__(self, x):
self.x = x
def approx(self, p):
n = 0
q = mpq(0, 1)
v = mpq(1, 1)
while True:
c = self.x.binseq(n)
if c == "-": v = mpq(-1, 1)
if c == ".": break
q = 2 * q
if c == "1": q += v
n = n + 1
k = 1
while k <= -p:
v = v / 2
c = self.x.binseq(n + k)
if c == "1": q += v
k = k + 1
return q
def bs_one_third(n):
if n == 1: return "."
if n % 2 == 0: return "0"
return "1"
def bs_almost_one(n):
if n == 0: return "1"
if n == 1: return "."
if n < 40: return "0"
return "1"
# Create binseq
y1 = REAL_bs(bs_almost_one)
# Create rational approx of the created binseq
z1 = REAL_ra_from_bs(y1)
# Create binseq
y2 = REAL_bs(bs_one_third)
# Create rational approx of the created binseq
z2 = REAL_ra_from_bs(y2)
print("y1: " + y1.as_string(50) + "\nz1: " + z1.asString(-50))
print("y2: " + y2.as_string(50) + "\nz2: " + z2.asString(-50))