Skip to content

Instantly share code, notes, and snippets.

@hiroto-takatoshi
Last active July 15, 2018 16:43
Show Gist options
  • Save hiroto-takatoshi/ec6449160123a5c046cbe16915d4dfe9 to your computer and use it in GitHub Desktop.
Save hiroto-takatoshi/ec6449160123a5c046cbe16915d4dfe9 to your computer and use it in GitHub Desktop.
calculates best reward when choosing 3 gambling options
import numpy as np
from scipy.optimize import minimize
k0 = 2.22
k1 = 6.2
k2 = 6.2
kk0 = 0.33
kk1 = 0.33
kk2 = 0.34
def objective(x):
return -(constraint4(x) * kk0 + constraint5(x) * kk1 + constraint6(x) * kk2) / (np.sum(x))
def constraint1(x):
return x[0] - 1
def constraint2(x):
return x[1]
def constraint3(x):
return x[2]
def constraint4(x):
return k0 * x[0] - x[0] - x[1] - x[2]
def constraint5(x):
return k1 * x[1] - x[0] - x[1] - x[2]
def constraint6(x):
return k2 * x[2] - x[0] - x[1] - x[2]
def constraint7(x):
t0 = k0 * x[0]
t1 = k1 * x[1]
t2 = k2 * x[2]
return (min(t0,t1,t2) - np.sum(x)) * 1.2 - (max(t0,t1,t2) - np.sum(x))
# initial guesses
n = 3
x0 = np.zeros(n)
x0[0] = 1.0
x0[1] = 1.0
x0[2] = 1.0
# optimize
b = (0.0,1000.0)
bnds = (b, b, b)
con1 = {'type': 'eq', 'fun': constraint1}
con2 = {'type': 'ineq', 'fun': constraint2}
con3 = {'type': 'ineq', 'fun': constraint3}
con4 = {'type': 'ineq', 'fun': constraint4}
con5 = {'type': 'ineq', 'fun': constraint5}
con6 = {'type': 'ineq', 'fun': constraint6}
con7 = {'type': 'ineq', 'fun': constraint7}
cons = ([con1,con2,con3,con4,con5,con6,con7])
solution = minimize(objective,x0,method='SLSQP',\
bounds=bnds,constraints=cons)
x = solution.x
xx = np.min(x)
x = x / xx
#print(solution)
# show final objective
print('Reward: ' + str(-objective(x)) + ' from ' + str(np.sum(x)) + ' (' + str(-objective(x) / np.sum(x) * 100) + '%)')
# print solution
print('Solution:')
print(round(np.sum(x*500)))
print(str(k0) + ' ' + str(round(x[0] * 500)) + ' ' + str(round(x[0] * 500 * k0)) )
print(str(k1) + ' ' + str(round(x[1] * 500)) + ' ' + str(round(x[1] * 500 * k1)) )
print(str(k2) + ' ' + str(round(x[2] * 500)) + ' ' + str(round(x[2] * 500 * k2)) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment