pythonで百発百中の大砲一門と百発一中の大砲百門撃ちあったらどちらが勝つかというコードを書いています。結果を表すグラフの作成方法がわかりません。教えていただけないでしょうか。
Q&A
解決したいこと
pythonで百発百中の大砲一門と百発一中の大砲百門撃ちあったらどちらが勝つかというコードを書いています。先に撃った場合と同時に攻撃した場合でどの程度結果が変わるかを検証しているのですがその結果を表すグラフを作成していたらエラーが起きてしまいました。グラフの作成方法を教えていただけないでしょうか。
発生している問題・エラー
実行結果とエラーです。
先行有利時の勝率: 1.0
同時攻撃時の勝率: [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-6582a67af622> in <cell line: 74>()
72
73 ax.plot(rate_range, win_rates_same, label='same')
---> 74 ax.plot(y=win_rate_pre, color='red', label='Advantage')
75
76 plt.xlabel('Rate')
1 frames
/usr/local/lib/python3.10/dist-packages/matplotlib/axes/_base.py in __call__(self, data, *args, **kwargs)
244 for pos_only in "xy":
245 if pos_only in kwargs:
--> 246 raise _api.kwarg_error(self.command, pos_only)
247
248 if not args:
TypeError: plot() got an unexpected keyword argument 'y'
### 該当するソースコード
pythonのソースコードです。
import random
import matplotlib.pyplot as plt
c1num = 1
rate1 = 1.0
c2num = 100
rate2 = 0.01
def sim1(c1num, rate1, c2num, rate2):
def shoot_cannon(rate):
if rate > random.random():
return True
else:
return False
c1num_copy = c1num
c2num_copy = c2num
while c1num_copy > 0 and c2num_copy > 0:
for _ in range(c1num_copy):
if shoot_cannon(rate1):
if c2num_copy > 0:
c2num_copy -= 1
else:
break
for _ in range(c2num_copy):
if shoot_cannon(rate2):
if c1num_copy > 0:
c1num_copy -= 1
else:
break
if c1num_copy == 0 and c2num_copy == 0:
return 0
elif c1num_copy == 0:
return 1
elif c2num_copy == 0:
return 2
else:
return 3
# 先行有利時のシミュレーションとグラフ
results_pre = []
for _ in range(10000):
result = sim1(c1num, rate1, c2num, rate2)
results_pre.append(result)
# 先行有利時の勝率
win_rate_pre = results_pre.count(1) / len(results_pre)
# 同時攻撃時のシミュレーションとグラフ
rate_range = [i * 0.01 for i in range(101)]
win_rates_same = []
for rate in rate_range:
results_same = []
for _ in range(10000):
result = sim1(c1num, rate, c2num, rate2)
results_same.append(result)
# 同時攻撃時の勝率
win_rate_same = results_same.count(1) / len(results_same)
win_rates_same.append(win_rate_same)
# 結果の比較の表示
print("先行有利時の勝率:", win_rate_pre)
print("同時攻撃時の勝率:", win_rates_same)
# グラフの表示
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(rate_range, win_rates_same, label='same')
ax.plot(y=win_rate_pre, color='red', label='Advantage')
plt.xlabel('Rate')
plt.ylabel('Win Rate')
plt.legend()
plt.show()
### 自分で試したこと
資料を見ながら試行錯誤してやってのですがどうしてもグラフの表示だけはうまくいきませんでした。お手数をおかけしますが教えていただけると幸いです。
0 likes