def HybridNewton(f, fprime, a, b, tol, maxIter): error = 10 * tol i = 0 newton = None x = bisection.bisection(f, a, b, tol, 4) xa = x[0] xb = x[1] if (x is None): return None while (i < maxIter): i += 1 x0 = .5 * (xa + xb) newton = newtonMethod.NewtonMethod(f, fprime, x0, tol, maxIter) if (newton is not None): return newton else: x = bisection.bisection(f, xa, xb, tol, 4) xa = x[0] xb = x[1] return newton
def test_bisection(): def f(x): if x < 2: return -1 elif x >= 3: return 1 else: return 0 r=bisection(f, 0, 10, 111) assert r == 2.5
def test_bisection_not_found(): def f(x): if x < 3.2: return -1 elif x >= 3.5: return 1 else: return 0 r=bisection(f, 0, 10, 100) assert r == 3.4375
def bisect(): data = request.json a = data["a"] b = data["b"] tol = data["tol"] iters = data["iters"] return dict(bisection(a, b, tol, iters))
def get_implied_volatilities(self, Ks, opt_prices): impvols = [] for i in range(len(Ks)): # Bind f(sigma) for use by the bisection method f = lambda sigma: self._option_valuation_(Ks[i], sigma) - opt_prices[i] impv = bisection(f, 0.01, 0.99, 0.0001, 100)[0] impvols.append(impv) return impvols
def get_implied_volatilities(self, Ks, option_prices): impvols = [] for i in range(len(Ks)): # Bind f(sigma) for use by the bisection method f = lambda sigma: self._option_valuation_(Ks[i], sigma ) - option_prices[i] impv = bisection(f, 0.01, 0.99, 0.0001, 100)[0] impvols.append(impv) return impvols
def TestRootFinding(): function1 = lambda x: x**2 - 3 funciton1prime = lambda x: 2 * x functionSin = lambda x: math.sin(math.pi * x) functionCos = lambda x: math.pi * math.cos(math.pi * x) tol = pow(10, -15) maxIter = 15 fixPoint1 = fixPoint.fixPoint(lambda x: (x + 3) / (x + 1), 2, tol, maxIter) bisection1 = bisection.bisection(function1, 1, 2, tol, maxIter) bisection2 = bisection.bisection(functionSin, .45, 1.45, tol, maxIter) newton1 = newtonMethod.NewtonMethod(function1, funciton1prime, 2, tol, maxIter) newton2 = newtonMethod.NewtonMethod(functionSin, functionCos, .45, tol, maxIter) secant1 = secant.Secant(function1, 1.5, 2, tol, maxIter) secant2 = secant.Secant(functionSin, .45, 1.45, tol, maxIter) hyNewton1 = hybridNewton.HybridNewton(function1, funciton1prime, 1, 3, tol, maxIter) hyNewton2 = hybridNewton.HybridNewton(functionSin, functionCos, 1, 1.5, tol, maxIter) hySecant1 = hybridSecant.hybridSecant(function1, 1, 2, tol, maxIter) hySecant2 = hybridSecant.hybridSecant(functionSin, 1, 1.5, tol, maxIter) print(fixPoint1, bisection1, bisection2, newton1, newton2, secant1, secant2, hyNewton1, hyNewton2, hySecant1, hySecant2, sep='\n')
def main(): n = int(input()) for k in range(0, n): amp = float(input()) eps = float(input()) (a, b) = isolation(amp) print('\nIsolation: ', (a, b)) print('Bissection: ', round(bisection(a, b, eps), 4)) print('Newton-Raphson: ',round(newton_raphson((a + b) * 0.5, eps), 4)) print('Secant: ',round(secant(a, b, eps), 4))
def main(argv): if (len(sys.argv) != 8): helper.helper() sys.exit(84) checker() flag = int(sys.argv[1]) a0 = int(sys.argv[2]) a1 = int(sys.argv[3]) a2 = int(sys.argv[4]) a3 = int(sys.argv[5]) a4 = int(sys.argv[6]) prec = int(sys.argv[7]) equa = [a0, a1, a2, a3, a4] if (flag == 1): bisection.bisection(equa, prec) elif (flag == 2): newton.newton(equa, prec) elif (flag == 3): secant.secant(equa, prec) exit(0)
def chooseAction(self, h, g, BEnergy, AoI, k): m_list = [] bisection_list = [] action_number = int(5) t0 = time.time() self.model.eval() th = time.time() th0 = th - t0 temp = torch.Tensor([np.hstack((h, g, BEnergy, AoI))]) t1 = time.time() t1h = t1 - th # print('===', temp.shape) predict = self.model(temp) predict = predict.detach().numpy() t2 = time.time() t12 = t2 - t1 # print('------',predict) list_in = [] list_in = np.argsort(-predict) # for i in range(k+1): # max=0 # flat=0 # for j in range(k+1): # if predict[0,j]>=max and (j not in list_in) : # max=predict[0,j] # flat=j # list_in.append(flat) t3 = time.time() t23 = t3 - t2 flat_number = 0 for node_to_trans in list_in[0]: m_index = [] for i in range(k + 1): if i == node_to_trans: m_index.append(1) else: m_index.append(0) B_bb = [x / 1000 for x in BEnergy] t4 = time.time() x = bisection(h / 10000, g / 10000, B_bb, AoI, m_index) t5 = time.time() t45 = t5 - t4 if x[0] > -1000: m_list.append(m_index) bisection_list.append(x) flat_number += 1 if flat_number == action_number: break t6 = time.time() t63 = t6 - t3 return m_list, bisection_list
def hybridSecant(f, a, b, tol, maxIter): i = 0 sec = None x = bisection.bisection(f, a, b, tol, 4) xa = x[0] xb = x[1] if (x is None): return None while (i < maxIter): i += 1 sec = secant.Secant(f, xa, xb, tol, maxIter) if (sec is not None): return sec else: x = bisection.bisection(f, xa, xb, tol, 4) xa = x[0] xb = x[1]
def get_implied_volatilities( self, Ks, opt_prices): """ Find implied volatilities given a list of market price inputs Ks as strike and price return vol-curve in imp_vol """ imp_vol = [] for i in range(len(Ks)): # Find f(sigma) by bisection method # f is defined as in-line function f = lambda sigma: self._option_valuation_(Ks[i],sigma)-opt_prices[i] vol = bisection( f, 0.01, 0.99, 0.0001, 100)[0] imp_vol.append(vol) return imp_vol
def do(): # Recebe número de movimentos e precisão n = int(input('Insert number of movements:\n')) eps = float(input('Insert precision(eps):\n')) # Para cada movimento for k in range(n): # Recebe o valor da amplitude amp = float(input(str(k + 1) + ': Insert amplitude:\n')) # Calcula o intervalo (a, b) = isolation(amp) # Inicializa lista que conterá os dados das tabelas dos 3 métodos data_list = [] # Calcula e salva aproximações de d, abs(b - a) ou abs(dk - d[k-1]), f(d) e erros relativos bisection_data, bisection_abs_diff = zip(*bisection(a, b, eps, amp)) bisection_applied = [f(x, amp) for x in bisection_data] bisection_re = re_per_method(bisection_data) data_list.append([bisection_data, bisection_applied, bisection_abs_diff, bisection_re]) nr_data, nr_abs_diff = zip(*newton_raphson((a + b) * 0.5, eps, amp)) nr_applied = [f(x, amp) for x in nr_data] nr_re = re_per_method(nr_data) data_list.append([nr_data, nr_applied, nr_abs_diff, nr_re]) secant_data, secant_abs_diff = zip(*secant(a, b, eps, amp)) secant_applied = [f(x, amp) for x in secant_data] secant_re = re_per_method(secant_data) data_list.append([secant_data, secant_applied, secant_abs_diff, secant_re]) # Salva na lista os nomes dos métodos, valor da amplitude e intervalo (a, b) data_list.append((['Bisection', 'Newton-Raphson', 'Secant'], amp, a, b, eps)) # Passa os dados para a função responsável pelas tabelas dino_plot(data_list)
def roots_legendre(n): roots = [] roots_inter = [] h = 2 / n a = -1 b = a + h legendre = form_legendre(n) while len(roots_inter) != n: roots_inter = [] while b <= 1: if legendre.get(a) * legendre.get(b) < 0: roots_inter.append([a, b]) a = b b += h h /= 2 a = -1 b = a + h for i in roots_inter: roots.append(bisection(i[0], i[1], 0.000001, legendre.get)) return roots
def test_methods(): assert round(bisection(0, 1, 1e-3, func), 9) == 0.337402344 assert round(newton_raphson(0.5, 1e-4, func, func_derived), 9) == 0.337606838 assert round(secant(0, 1, 5e-4, func), 9) == 0.337634621
def sample(): brachistochrone_x = lambda r, t, f_x: f_x + (r * (t - sin(t))) brachistochrone_y = lambda r, t, f_y: f_y + (r * (-1 + cos(t))) segments = 20 x1 = 20 y1 = 40 x2 = 40 y2 = 20 # x1 = 1 # y1 = 1 # x2 = 5 # y2 = -5 # a = -1.04172 xs = [] ys = [] xns = [] yns = [] t = abs(compute_angle(0, 0, x2, y2) - compute_angle(0, 0, x1, y1)) solve_x = lambda y, h, k, r: sqrt(r**2 - (y - k)**2) + h solve_y = lambda x, h, k, r: sqrt(r**2 - (x - h)**2) + k top_f = lambda x, h, k, r: solve_y(x, h, k, r) bottom_f = lambda x, h, k, r: (-1 * solve_y(x, h, k, r)) + (2 * k) slope = lambda x1, y1, x2, y2: (y2 - y1) / (x2 - x1) # solve for the y of a given line. needs 2 points on the line and point x to calculate. linear = lambda x, x1, y1, x2, y2: (slope(x1, y1, x2, y2) * x) + (y1 - ( slope(x1, y1, x2, y2) * x1)) print("t: " + str(t)) # for theta in thetas: # bx = brachistochrone_x(a, theta, x1) # by = brachistochrone_y(a, theta, y1) # # xs.append(rotate_point(x1, y1, bx, by, 180)) # # ys.append(rotate_point(x1, y1, bx, by, 180)) # xs.append(bx) # ys.append(by) # print("(" + str(bx) + ", " + str(by) + ")") # t_equation = lambda x, y, t : ((y * (t - sin(radians(t)))) - (x * (1 - cos(radians(t))))) def t_equation(x, y, t): # print("x: " + str(x) + ", y: " + str(y) + ", t: " + str(t)) # return ((y * (t - sin(radians(t)))) - (x * (1 - cos(radians(t))))) return ((y * (t - sin(t))) - (x * (1 - cos(t)))) delta_x = (0 - x1) delta_y = (0 - y1) off_x = -1 * delta_x off_y = -1 * delta_y x_val = x2 x_val *= 1 if x_val >= 0 else -1 x_val += delta_x y_val = y2 y_val *= 1 if y_val >= 0 else -1 y_val += delta_y off_x *= 2 if ((x2 < 0) ^ (x_val < 0)) else 1 off_y *= 2 if ((y2 < 0) ^ (y_val < 0)) else 1 print("x2: " + str(x2) + ", y2: " + str(y2)) print("x_val: " + str(x_val) + ", y_val: " + str(y_val)) print("delta_x: " + str(delta_x) + ", delta_y: " + str(delta_y)) print("off_x: " + str(off_x) + ", off_y: " + str(off_y)) t = bisection(t_equation, [0, 359], times=25, args=[x_val, y_val]) print("t: " + str(t)) # for i, x in enumerate(range(x1, x2+1, round((abs(x2 - x1) / segments)))): # # t = 15.4505#(180. / segments) * i # bx = brachistochrone_x(a, t, x) # by = brachistochrone_y(a, t, linear(x, x1, y1, x2, y2)) # # xs.append(rotate_point(x1, y1, bx, by, 180)) # # ys.append(rotate_point(x1, y1, bx, by, 180)) # xs.append(bx) # ys.append(by) # print("(" + str(bx) + ", " + str(by) + ")") i = 0 j = 0 # off_x /= segments # off_y /= segments # rt = radians(t) d = t / segments r = y_val / (1 - cos(t)) print("r: " + str(r)) while i <= t: bx = brachistochrone_x(r, i, (x1)) by = brachistochrone_y(r, i, (y1)) xs.append(bx) ys.append(by) xns.append((bx - x1)) # + (off_x)) yns.append((by - y1)) # + (off_y)) i += d j += 1 if x2 != x_val: # xd = (abs(x2) - abs(x_val)) / segments xd = abs((x2 - x1) / x_val) print("xd: " + str(xd)) xns = [(xd * x) + x1 for i, x in enumerate(xns)] # xns = [(x1 + x) * off_x for i, x in enumerate(xns)] if y2 != y_val: # yd = (abs(y2) - abs(y_val)) / segments yd = abs((y2 - y1) / y_val) print("yd: " + str(yd)) yns = [(yd * y) + y1 for i, y in enumerate(yns)] # yns = [(y1 + y) * off_y for i, y in enumerate(yns)] for x, y in zip(xs, ys): print("(x,y): (" + str(x) + "," + str(y) + ")") for x, y in zip(xns, yns): print("(xn,yn): (" + str(x) + "," + str(y) + ")") xsys_plot = plt.plot(xs, ys, label="xsys") xnsyns_plot = plt.plot(xns, yns, label="xnsyns") h = 100 k = 100 r = 100 graph(top_f, range(0, 201), (h, k, r)) graph(bottom_f, range(0, 201), (h, k, r)) plt.legend(loc="upper left") plt.ylabel("y") plt.xlabel("x") plt.gca().set_aspect("equal") plt.plot(x1, y1, 'r+') plt.plot(x2, y2, 'r+') plt.show()
from bisection import bisection from math import sin def f(x): return x - (x-1)*sin(x) x, iter = bisection(f, -2, 1, 1E-5) print x, iter
import sys usage = '%s f-formula a b [epsilon]' % sys.argv[0] try: f_formula = sys.argv[1] a = float(sys.argv[2]) b = float(sys.argv[3]) except IndexError: print usage; sys.exit(1) try: # is epsilon given on the command-line? epsilon = float(sys.argv[4]) except IndexError: epsilon = 1E-6 # default value from scitools.StringFunction import StringFunction from math import * # might be needed for f_formula f = StringFunction(f_formula) from bisection import bisection root, iter = bisection(f, a, b, epsilon) if root == None: print 'The interval [%g, %g] does not contain a root' % (a, b) sys.exit(1) print 'Found root %g\nof %s = 0 in [%g, %g] in %d iterations' % \ (root, f_formula, a, b, iter)
def test_sin_bisection(self): result = bisection(sin, [-2, 3], 1e-03) self.assertEqual(-0.00018310546875, result)
# root = newtonRaphson(function, dervivative of function, lower bracket, upper bracket, tolerance) root = newtonRaphson.newtonRaphson(f,df,e,k,tol=1.0e-9) # The root is returned as one number. ########################################################################### # In-build fsolve Method (returns both roots in an array and so the upper and lower brackets are of the entire interval in which all roots lie). from scipy.optimize import fsolve # root = fsolve(function, [lower limit of INTERVAL, upper limit of INTERVAL]) root = fsolve(f,[intlow,intupp]) # The roots are returned in array and are seperated out and defined individually below. 1stroot = root[0] 2ndroot = root[1] ########################################################################### # Bisection Method (do this for each root) import bisection # root = bisection.bisection(function, lower bracket, upper bracket, switch=1, tolerence) root = bisection.bisection(f,x1,x2,switch=1,tol=1.0e-9) # The root is returned as one number. ###########################################################################
def test_cos_bisection(self): result = bisection(cos, [-2, 1], 1e-03) self.assertEqual(-1.5704345703125, result)
def y(E,e,a=1.496e8): b=a*np.sqrt(1-e**2) return b*np.sin(E) time = [91,182,273] eccentricity = 0.0167 a=1.496e8 a1 = 0 b1 = 2*np.pi+1 T = 365.25635 #print('roots',bis.iteration(f,a1,b1,epsilon=1e-10)) print('\nPunto a') for t in time: SOL=bis.bisection(f,a=a1,b=b1,e=eccentricity,w=2*np.pi/T,t=t,epsilon=1e-22) angle = SOL[0][0] print('For t: {}\n E is {}\n x is {} = {} AU\n y is {} = {} AU\n iterations {}\n'.format(t,angle,x(E=angle),x(E=angle)/a,y(angle,e=eccentricity),y(angle,e=eccentricity)/a,SOL[1])) print('\nPunto b') for t in time: SOL=bis.bisection(f,a=a1,b=b1,e=1,w=2*np.pi/T,t=t,epsilon=1e-22) angle = SOL[0][0] print('For t: {}\n E is {}\n x is {} = {} AU\n y is {} = {} AU\n iterations {}\n'.format(t,angle,x(E=angle),x(E=angle)/a,y(angle,e=eccentricity),y(angle,e=eccentricity)/a,SOL[1]))
def bicOpt(): args = inspect.getfullargspec(bisection)[0] return bisection(*defineParams(args))
by using of Bisection method. """ import numpy as np import matplotlib.pyplot as plt from bisection import bisection def f(x): return 2 * np.cos(x) + (1 - x) #* np.exp(-x) x = np.linspace(-10., 10., 200) y = f(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.show() xresult1 = bisection(f, 1, 3) print('solution(1) = ', xresult1) xresult2 = bisection(f, 5, 7) print('solution(2) = ', xresult2) xresult3 = bisection(f, 8, 9) print('solution(3) = ', xresult3) solution(1) = 1.3797576182114426 solution(2) = 5.000000000029104 solution(3) = 8.000000000029104
def test_exp_plus_tan(self): f = lambda x: exp(x) + tan(x) result = bisection(f, [-1, 0], 1e-03) self.assertEqual(-0.53173828125, result)
from regula_falsi import regula_falsi from newton_raphson import newton_raphson, derive ''' A crude approximation of π by finding the root of the sine function which lies between 3 and 4. The sine function itself has been approximated as a partial sum of its Taylor series around 0. ''' TERMS = 16 DELTA = 1e-12 EPSILON = 1e-12 def sin(x): term = x total = x for n in range(TERMS): term *= -1 * x * x / ((2 * n + 2) * (2 * n + 3)) total += term return total if __name__ == '__main__': pi, iterations = bisection(sin, 3, 4, delta=DELTA) print(f"BISECTION : pi = {pi}, tolerance {DELTA}, {iterations} iterations") pi, iterations = regula_falsi(sin, 3, 4, epsilon=EPSILON) print(f"REGULA-FALSI : pi = {pi}, tolerance {EPSILON}, {iterations} iterations") pi, iterations = newton_raphson(sin, derive(sin), 3, epsilon=EPSILON) print(f"NEWTON-RAPHSON : pi = {pi}, tolerance {EPSILON}, {iterations} iterations")
import math if __name__ == '__main__': max_iter = 200 #Problem 1 print("Problem 1: Find real roots of f(x) = -12 - 21x - 18x^2 - 2.75x^3 in the range x: [-10, 10].") prob_1_func = lambda x: -12 - 21*x - 18*(x**2) - 2.75*(x**3) low_limit = -10 upper_limit = 10 stop_criterion = 0.001 root_brackets = incremental(prob_1_func, low_limit, upper_limit, 1/stop_criterion) print("Search within the brackets found by the 'incremental' function!") for bracket in root_brackets: print("--Within bracket: "+str(bracket)) output_bisection = bisection(prob_1_func, bracket[1], bracket[0], max_iter, stop_criterion) root_b = output_bisection[0] print("\t--'Bisection' finds a root at: "+str(root_b)) output_false_pos = false_position(prob_1_func, bracket[1], bracket[0], max_iter, stop_criterion) root_fp = output_false_pos[0] print("\t--'False Position' finds a root at: "+str(root_fp)) #Problem 2 print("\nProblem 2: The volume of a tank is V (m^3) = pi*h^2*(3*R-h)/3") print("Find the height (m) {between 0 and R} to fill a tank of radius 3 (m) so that the volume is 30 (m^3).") solve_for_volume = lambda R, h: math.pi*(h**2)*((3*R - h)/(3)) prob_2_func = lambda V, R, h: solve_for_volume(R, h)-V volume = 30 # meters cubed radius = 3 # meters solve_for_h = lambda h: prob_2_func(volume, radius, h) stop_criterion = 0.001
else: # test i_idx = i - n + num_test + split_idx h = channel_h[i_idx, :] g = channel_g[i_idx, :] # AoI = ProcessAoI[i_idx,:] # BEnergy = Energy[i_idx,:] # the action selection must be either 'OP' or 'KNN' m_list = [] m_list = mem.decode(h, g, Energy_train, AoI, N, decoder_mode) r_list = [] Energy_now = [x / 1000 for x in Energy_train] for m in m_list: r_list.append(bisection(h / 10000, g / 10000, Energy_now, AoI, m)[0]) # encode the mode with largest reward # try: Energy_bb = [x for x in ( bisection(h / 10000, g / 10000, Energy_now, AoI, m_list[np.argmax(r_list)])[2])] Energy_train = [x * 1000 for x in Energy_bb] AoI = [x for x in (bisection(h / 10000, g / 10000, Energy_now, AoI, m_list[np.argmax(r_list)])[3])] mem.encode(h, g, Energy_train, AoI, m_list[np.argmax(r_list)]) # the main code for DROO training ends here count = 0 # start the calculate AverageAoI # the following codes store some interested metrics for illustrations # memorize the largest reward rate_his.append(np.max(r_list))
from golden_ratio import golden_ratio from bisection import bisection from secant import secant if __name__ == '__main__': print("\n GOLDEN RATIO") x, fx, it = golden_ratio(a, b, eps_1) print(f"\nfor eps = {eps_1}", "\nx* = ", x, "\nf(x*) = ", fx, "\niteration number = ", it) x, fx, it = golden_ratio(a, b, eps_2) print(f"\nfor eps = {eps_2}", "\nx* = ", x, "\nf(x*) = ", fx, "\niteration number = ", it) print("\n BISECTION") x, fx, it = bisection(a, b, eps_1) print(f"\nfor eps = {eps_1}", "\nx* = ", x, "\nf(x*) = ", fx, "\niteration number = ", it) x, fx, it = bisection(a, b, eps_2) print(f"\nfor eps = {eps_2}", "\nx* = ", x, "\nf(x*) = ", fx, "\niteration number = ", it) print("\n SECANT") x, fx, it = secant(a, b, eps_1) print(f"\nfor eps = {eps_1}", "\nx* = ", x, "\nf(x*) = ", fx, "\niteration number = ", it) x, fx, it = secant(1.7, 2, eps_2) print(f"\nfor eps = {eps_2}", "\nx* = ", x, "\nf(x*) = ", fx, "\niteration number = ", it) input("\n\nPRESS ANY KEY TO CLOSE")
import numpy as np #数値計算用モジュール import bisection def func_f1(x): return x**2.0 -3.0 solution1 = bisection.bisection(func_f1, 1.0, 2.0, error=1e-15) bisection.visualization(func_f1, solution1-1.0, solution1+1.0, solution1) def func_f2(x): return np.arctan(x) solution2 = bisection.bisection(func_f2, -1.0, 1.0) bisection.visualization(func_f2, solution2-1.0, solution2+1.0, solution2)
#-*- coding: utf-8 -*- """ Program to calculate the root plt """ import bisection as bis import numpy as np import matplotlib.pyplot as plt # Function to calculate the roots on a given interval def f(x): y = 3 * x**5 + 5 * x**4 - x**3 return y a1 = -10 b1 = 10 SOL = bis.bisection(f, a=a1, b=b1, epsilon=1e-22) print('The roots of the function on [{}:{}] are {}'.format(a1, b1, SOL[0]))
import sys usage = '%s f-formula a b [epsilon]' % sys.argv[0] try: f_formula = sys.argv[1] a = float(sys.argv[2]) b = float(sys.argv[3]) except IndexError: print usage sys.exit(1) try: # is epsilon given on the command-line? epsilon = float(sys.argv[4]) except IndexError: epsilon = 1E-6 # default value from scitools.StringFunction import StringFunction from math import * # might be needed for f_formula f = StringFunction(f_formula) from bisection import bisection root, iter = bisection(f, a, b, epsilon) if root == None: print 'The interval [%g, %g] does not contain a root' % (a, b) sys.exit(1) print 'Found root %g\nof %s = 0 in [%g, %g] in %d iterations' % \ (root, f_formula, a, b, iter)
if i> 0 and i % Delta == 0: # index counts from 0 if Delta > 1: max_k = max(k_idx_his[-Delta:-1]) +1; else: max_k = k_idx_his[-1] +1; K = min(max_k +1, N) h = channel[i] # the action selection must be either 'OP' or 'KNN' m_list = mem.decode(h, K, decoder_mode) r_list = [] for m in m_list: r_list.append(bisection(h/1000000, m)[0]) # encode the mode with largest reward mem.encode(h, m_list[np.argmax(r_list)]) # the main code for DROO training ends here rate_his.append(np.max(r_list)) # record the index of largest reward result = np.array(np.loadtxt("result2.txt",delimiter=',')) rate_his_radio.append(np.max(r_list)/result[i]) k_idx_his.append(np.argmax(r_list)) # record K in case of adaptive K K_his.append(K) mode_his.append(m_list[np.argmax(r_list)])