ich habe die Aufgabe, zu einer gegebenen Testfunktion die eigentliche Funktion zu schreiben.
Ziel ist es, eine Tabelle mit Funktionswerten auszugeben. Dabei ist die linke Spalte die der y-Werte, die unterste Zeile sind die x-Werte.
Hier mal meine Lösung:
Code: Alles auswählen
def write_table_to_file(f, xmin, xmax, nx, ymin, ymax, ny, width = 10, decimals = 5, filename = 'table.dat'):
x = np.linspace(xmin, xmax, nx+1)
y = np.flip(np.sort(np.linspace(ymin, ymax, ny+1)))
vals = f(x, y[:, np.newaxis])
with open(filename, 'w') as outfile:
for yval, row in zip(y, vals):
outfile.write(f"{yval:{width}.{decimals}g}")
for col in row:
outfile.write(f"{col:{width}.{decimals}g}")
outfile.write('\n')
outfile.write('\n')
outfile.write(width * ' ')
for xval in x:
outfile.write(f"{xval:{width}.{decimals}g}")
def test_write_table_to_file():
filename = 'tmp.dat'
write_table_to_file(f=lambda x, y: x + 2*y,
xmin = 0, xmax = 2, nx = 4,
ymin = -1, ymax = 2, ny = 3,
width = 5, decimals = None, # soll %5g entsprechen
filename = filename)
# Load text in file and compare with expected results
with open(filename, 'r') as infile:
computed = infile.read()
expected = """\
2 4 4.5 5 5.5 6
1 2 2.5 3 3.5 4
0 0 0.5 1 1.5 2
-1 -2 -1.5 -1 -0.5 0
0 0.5 1 1.5 2"""
assert computed == expected
import numpy as np
test_write_table_to_file()
Vorgabe ist, dass width = 10, decimals = 1 %10.1g entspricht und width = 5, decimals = None soll zu %5g werden (da wird die alte Formatierungsweise verwendet).
Für decimals=5 z. B. funktioniert meine Funktion, aber mit dem None weiß ich nichts anzufangen.
Liebe Grüße