Skip to content

Instantly share code, notes, and snippets.

@KatsuhiroMorishita
Last active March 15, 2017 00:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KatsuhiroMorishita/ffa12a1b0791d35f49632596862610a3 to your computer and use it in GitHub Desktop.
Save KatsuhiroMorishita/ffa12a1b0791d35f49632596862610a3 to your computer and use it in GitHub Desktop.
数値計算の計算結果を評価するPythonスクリプトです。
"""
数値計算の計算結果を評価する
"""
def flatten(foo):
""" 多次元配列を1次元配列に変換する
"""
series = []
for mem in foo:
if isinstance(mem, list):
bar = flatten(mem)
series += bar
elif isinstance(mem, complex):
series.append(mem.real)
series.append(mem.imag)
else:
#print(mem)
series.append(mem)
return series
def check(o, t, th=0.001):
""" 2つのベクトルの中身が数値計算的に等しいかどうか確認する
return
True: 等しい
False: 等しくない
"""
# 次元数の確認
if len(o) != len(t):
print("--0--, length not match")
return False
# intをfloatに変更
_o = [float(x) if isinstance(x, int) else x for x in o]
_t = [float(y) if isinstance(y, int) else y for y in t]
# 型をチェック 一方がNoneでもFalseとなる
c = [type(x) == type(y) for x,y in zip(_o, _t)]
if False in c:
print("--1--")
return False
# 完全一致だとTrue NoneでもOK 数値は処理したくない
__o = [True if x == y or x is y else x for x,y in zip(_o, _t)]
__t = [True if x == y or x is y else y for x,y in zip(_o, _t)]
# 文字列の不一致を数値化
_o = [0 if isinstance(x, str) else x for x,y in zip(__o, __t)]
_t = [1 if isinstance(x, str) else y for x,y in zip(__o, __t)]
print("--2--", _o, _t)
# ベクトル内の要素を個別にチェック
ans = [(abs(x - y) / max(x, y)) < th for x,y in zip(_o, _t)]
print("--3--", ans)
return False in ans == False
#a = [10.1, "解なし", False, [10, "解なし", 45, [10, 20, 30]]]
a = [10.1, "解なし", False, [10, 0.001, 45, [10, 20, 10+3j]]]
b = [10, "解あり", True, [10, 20, 30, [10, 20, 30-23j]]]
_a = flatten([a])
_b = flatten([b])
print(check(_a, _b))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment