def e_Calculator(): print("'e' (Euler's number) Calculator") digits = int( input('Enter the number of digits you want for your value of e : ')) steps = int( input( 'Enter the maximum number of steps desired (if unsure, enter 500) : ' )) prec = 3 * digits gc().prec = prec maxSteps = steps # You should stop when k! > 10^n # See Gourdon & Sebah (2001) Mathematical constants and computation, Jan 11 s = 1 for k in range(1, maxSteps + 1): numerator = 1 denominator = factorial(k) s += Dec(1) / factorial( k ) # Note, if you do Dec(1/factorial(k)), your answer will diverge after the 16th decimal place e = s e = Dec(str(e)[:digits + 1]) # Drop few digits of precision for accuracy print(f'Your value for e = {e}') print( '\nThe value obtained should not diverge from http://www.numberworld.org/digits/E/ or other reference value.' ) print('But if it does, then you must increase the number of steps.') print( 'However, increasing the number of digits or steps comes at the cost of processor power.' )
def _fraction( self, qty: Dec, divisor: Dec = Dec(3), minimum: Dec = Dec(1)) -> Dec: """ Return a fraction of the given quantity, with a minimum. Used for depleting reserves gradually. """ return max(hm.round_decimal(qty / divisor), min(minimum, qty))
def __init__(self, point, length, angle, dirang=Dec(), coords = Point(Dec(), Dec())): self.point = point self.len = length self.ang = angle self.dirang = dirang self.coords = coords self.dx, self.dy = Dec(), Dec()
def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.last_bet_end: int = random.randint(-20, 10) '''How long since the last market maker's "bet"''' self.minimal_wait: int = 10 '''How long will the market maker wait since it's last "bet" to let the market move on its own''' self.bet_duration: int = 30 '''How long will the market maker do its "bet" for''' self.bet_percentage: Dec = Dec('1') ''' How much of it's wealth will the market maker use on a "bet" The bot will constantly update the orders on either side to use all it's wealth multiplied by the percentage value ''' self.initial_bet_margin: Dec = Dec('0.05') ''' How off the expected price gradient will the bets be placed initially ''' self.ending_bet_margin: Dec = Dec('0.01') ''' How close the bets get at the end ''' self.trade_market = random.choice([ self.havven_fiat_market, self.nomin_fiat_market, self.havven_nomin_market ]) self.current_bet: Optional[Dict[str, Any[str, int, Dec, 'ob.LimitOrder']]] = None
def place_ask_func(self, time_in_effect: int, gradient: Dec, start_price: Dec) -> "ob.Ask": """ Place an ask at a price dependent on the time in effect and gradient based on the player's margins The price chosen is the current predicted price (start + gradient * time_in_effect) multiplied by the current bet margin 1+(fraction of time remaining)*(max-min margin)+min_margin """ price = start_price + Dec(gradient * time_in_effect) multiplier = 1 + ( (Dec((self.bet_duration - time_in_effect) / self.bet_duration) * (self.initial_bet_margin - self.ending_bet_margin)) + self.ending_bet_margin) if self.trade_market == self.nomin_fiat_market: return self.place_nomin_fiat_ask_with_fee( self.available_nomins * self.bet_percentage, price * multiplier) elif self.trade_market == self.havven_fiat_market: return self.place_havven_fiat_ask_with_fee( self.available_havvens * self.bet_percentage, price * multiplier) elif self.trade_market == self.havven_nomin_market: return self.place_havven_nomin_ask_with_fee( self.available_nomins * self.bet_percentage, price * multiplier)
def PI(maxK=70, prec=1008, disp=1007, K=6, M=1, L=13591409, X=1, S=13591409, ki=1): gc().prec = prec ''' state = getState(maxK, prec, disp) if state != None: K,M,L,X,S,ki = int(state['K']),int(state['M']),int(state['L']),int(state['X']),Dec(state['S']),int(state['k']) ''' for k in range(ki, maxK + 1): M = (K**3 - 16 * K) * M // k**3 L += 545140134 X *= -262537412640768000 S += Dec(M * L) / X K += 12 #saveState(K,M,L,X,S,k,maxK,prec,disp) print(f'k:{k}', flush=True) pi = 426880 * Dec(10005).sqrt() / S pi = Dec(str(pi)[:disp]) print("PI(maxK={} iterations, gc().prec={}, disp={} digits) =\n{}".format( maxK, prec, disp, pi)) return pi
def update_e_factor(e_factor: Dec, score: int) -> Dec: inverse_score = 5 - score shift = Dec(0.1) - \ (inverse_score * (Dec(0.08) + (inverse_score * Dec(0.02)))) e_factor_prime = e_factor + shift return max(Dec(1.3), e_factor_prime)
def __init__( self, unique_id: int, havven: "model.HavvenModel", fiat: Dec = Dec(0), havvens: Dec = Dec(0), nomins: Dec = Dec(0), profit_threshold: Dec = Dec('0.05') ) -> None: super().__init__(unique_id, havven, fiat=fiat, havvens=havvens, nomins=nomins) self.profit_threshold = profit_threshold """ This arbitrageur will only trade if it can make a profit higher than this fraction. """ # Cached values of the amount available in arb cycles for performance # and neatness. self.havven_fiat_bid_qty = Dec(0) self.havven_nomin_bid_qty = Dec(0) self.nomin_fiat_bid_qty = Dec(0) self.nomin_fiat_ask_qty = Dec(0) self.havven_nomin_ask_qty = Dec(0) self.havven_fiat_ask_qty = Dec(0)
def lin_of_lin_sequence_series_dec(n): a = 1 b = 1 changes = 0 choosen = 0 increments = [] s = Dec(0) dec_1 = Dec(1) for i in range(1, n + 1): amount = 1 if choosen == 0: a = 2 * a + 1 while a < b: a = 2 * a + 1 amount += 1 increments.append((amount, "a")) s += dec_1 / Dec(a) elif choosen == 1: b = 3 * b + 1 while b < a: b = 3 * b + 1 amount += 1 increments.append((amount, "b")) s += dec_1 / Dec(b) choosen = (choosen + 1) % 2 changes += 1 print("i: {}, s: {}".format(i, s)) print("increments:\n{}".format(increments)) globals()["increments"] = increments return s
def calc_ln(x, iterations): s = Dec("0") for j in xrange(0, iterations): i = j * 2 + 1 s += 1 / Dec("{}".format(i)) * ((x - Dec("1")) / (x + Dec("1")))**i return Dec("2") * s
def hms(deg): assert isinstance(deg, Dec) pdeg, pmm = divmod(deg, 1) pmm = pmm * Dec(60) pmm, pss = divmod(pmm, 1) pss = pss * Dec(60) return Deg(pdeg, pmm, pss)
def patch_get_close(self, date_time: datetime): if date_time == TIME2: return Dec(1100) if date_time == TIME3: return Dec(1200) # raise ValueError("Patch called unexpectedly for time {}".format(date_time)) return Dec()
def arc_tan_it(x, n): ''' Arctan nème terme ''' numerator = math.pow(-1, n) * math.pow(x, 2 * n + 1) denominator = 2 * n + 1 return Dec(numerator) / Dec(denominator)
def gen_prob(file): with open(file, "r", encoding="utf8") as data_file: loaded_dictionaries = json.loads(data_file.read()) all_prob = [] total_probability = Dec(1) for w in loaded_dictionaries: if w == "pos" or w == "neg": total = loaded_dictionaries["total_words_count"]["count"] unique = loaded_dictionaries["total_words_count"]["unique"] prob = Dec( (loaded_dictionaries[w]["count"] + 1) / (total + unique)) loaded_dictionaries[w]["prob"] = prob elif "class" in loaded_dictionaries[w]: class_name = loaded_dictionaries[w]["class"] total = (loaded_dictionaries[class_name]["count"]) unique = (loaded_dictionaries[class_name]["unique"]) prob = Dec( (loaded_dictionaries[w]["count"] + 1) / (total + unique)) loaded_dictionaries[w]["prob"] = prob total_probability *= Dec(prob) if total_probability == float(0): print("{} : {}".format(w, loaded_dictionaries[w])) break all_prob.append(total_probability) loaded_dictionaries["total_words_count"]["prob"] = total_probability with open("all_prob.bayes", "w", encoding="utf8") as file_test: file_test.write(str(all_prob)) with open(file, "w", encoding="utf8") as data_file: simplejson.dump(loaded_dictionaries, data_file)
def chudnovsky(precision, max_iter=100, timeout=False): """ Calculates pi using the Chudnovsky algorithm: https://en.wikipedia.org/wiki/Chudnovsky_algorithm Runs in O(n log(n)^3). :param precision: The level of precision to be used :param max_iter: The maximum number of iterations to be used :param timeout: The maximum number of seconds to pass before refusing to continue summation. Note that this can potentially drastically affect the accuracy of the calculation. :return: Pi to some level of precision """ gc().prec = precision + 1 k_term = 6 multinomial_term = 1 linear_term = 13591409 exponential_term = 1 current_sum = 13591409 start = time.time() for k in range(1, max_iter + 1): if timeout and time.time() > start + timeout: break multinomial_term = (k_term**3 - 16 * k_term) * multinomial_term // k**3 linear_term += 545140134 exponential_term *= -262537412640768000 current_sum += Dec(multinomial_term * linear_term) / exponential_term k_term += 12 c_term = 426880 * Dec(10005).sqrt() pi = c_term / current_sum pi = Dec(str(pi)[:precision]) # Only return up to the level of precision return pi
def guess(inp): if isinstance(inp, str) and '-' in inp: deg, mm, ss = inp.split('-') ddeg, dmm, dss = Dec(deg), Dec(mm), Dec(ss) return ddeg + dmm / 60 + dss / 3600 else: return Dec(inp)
def setup(self, init_value): if self.primary_currency == "fiat": self.fiat = self.model.manager.round_decimal(init_value * Dec(3)) elif self.primary_currency == "nomins": self.fiat = self.model.manager.round_decimal(init_value * Dec(3)) elif self.primary_currency == "havvens": self.model.endow_havvens( self, self.model.manager.round_decimal(init_value * Dec(3)))
def approx_decreasing_chain_fraction(n=100): dec_x = Dec(1) # lst_dec_x = [dec_x] for i in range(1, n, 1): dec_x = Dec(i*2+1)+Dec(i*2)/dec_x # lst_dec_x.append(dec_x) dec_x = Dec(i*2+2)/dec_x return dec_x
def _add_central_bank(self, unique_id, num_agents, init_value): central_bank = ag.CentralBank(unique_id, self.havven_model, fiat=Dec(num_agents * init_value), nomin_target=Dec('1.0')) self.havven_model.endow_havvens(central_bank, Dec(num_agents * init_value)) self.havven_model.schedule.add(central_bank) self.agents["others"].append(central_bank)
def step(self) -> None: if self.nomin_havven_order is not None: if self.model.manager.time >= self.nomin_havven_order[ 0] + self.trade_duration: self.nomin_havven_order[1].cancel() self.nomin_havven_order = None if self.nomin_fiat_order is not None: if self.model.manager.time >= self.nomin_fiat_order[ 0] + self.trade_duration: self.nomin_fiat_order[1].cancel() self.nomin_fiat_order = None if self.fiat_havven_order is not None: if self.model.manager.time >= self.fiat_havven_order[ 0] + self.trade_duration: self.fiat_havven_order[1].cancel() self.fiat_havven_order = None if self.available_nomins > 0: if len(self.model.datacollector.model_vars['0']) > 0: havven_supply = self.model.datacollector.model_vars[ 'Havven Supply'][-1] fiat_supply = self.model.datacollector.model_vars[ 'Fiat Supply'][-1] # buy into the market with more supply, as by virtue of there being more supply, # the market will probably have a better price... if havven_supply > fiat_supply: order = self.place_havven_nomin_bid_with_fee( self.available_nomins * self.sell_rate, self.havven_nomin_market.price * (Dec(1) - self.trade_premium)) if order is None: return self.nomin_havven_order = (self.model.manager.time, order) else: order = self.place_nomin_fiat_ask_with_fee( self.available_nomins * self.sell_rate, self.nomin_fiat_market.price * (Dec(1) + self.trade_premium)) if order is None: return self.nomin_fiat_order = (self.model.manager.time, order) if self.available_fiat > 0 and not self.fiat_havven_order: order = self.place_havven_fiat_bid_with_fee( hm.round_decimal(self.available_fiat * self.sell_rate), self.havven_fiat_market.price * (Dec(1) - self.trade_premium)) if order is None: return self.fiat_havven_order = (self.model.manager.time, order) if self.available_havvens > 0: self.escrow_havvens(self.available_havvens) issuable = self.max_issuance_rights() - self.issued_nomins if hm.round_decimal(issuable) > 0: self.issue_nomins(issuable)
def log_dec_num(x): if not isinstance(x, Dec): x = Dec(x) assert x > Dec("0") y_start = Dec(np.log(float(x))) print("y_start: {}".format(y_start)) diff = x - e**y_start print("diff: {}".format(diff))
def get_paid_received(self, who): with self.db as ledger: cur = ledger.cursor() cur.execute("SELECT Amount FROM Transactions WHERE WhoFrom=:who", {'who': who}) paid = sum([Dec(str(record[0])) for record in cur.fetchall()]) cur.execute("SELECT Amount FROM Transactions WHERE WhoTo=:who", {'who': who}) received = sum([Dec(str(record[0])) for record in cur.fetchall()]) return (paid, received)
def approx_increasing_chain_fraction(n=100): dec_x = Dec(n*2-1) # lst_dec_x = [dec_x] # lst_dec_x = [Dec(dec_x.to_eng_string())] for i in range(n-1, 0, -1): dec_x = Dec(i*2-1)+Dec(i*2)/dec_x # lst_dec_x.append(dec_x) # lst_dec_x.append(Dec(dec_x.to_eng_string())) return dec_x
def chudnovsky_pi_summation(n): # Thanks Chudnovsky, whoever you are! pi = Dec(0) for k in range(n): pi += (Dec(-1)**k) * (Dec(factorial(6 * k)) / ((factorial(k)**3) * (factorial(3 * k))) * (13591409 + 545140134 * k) / (640320**(3 * k))) pi = pi * Dec(10005**0.5) / 4270934400 return float(pi**(-1))
def _helper(d): if d["symbol"].endswith("USD") or d["symbol"].endswith("USDT"): in_usd = Dec(d["volumeQuote"]) elif d["symbol"].endswith("ETH"): in_usd = Dec(d["volumeQuote"]) * eth_usd elif d["symbol"].endswith("BTC"): in_usd = Dec(d["volumeQuote"]) * btc_usd else: raise ValueError("Could not convert %s" % d["symbol"]) return d["symbol"], in_usd
def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.fiat_havven_order: Optional[Tuple[int, "ob.Bid"]] = None """The time the order was placed as well as the fiat/hvn order""" self.nomin_havven_order: Optional[Tuple[int, "ob.Bid"]] = None self.nomin_fiat_order: Optional[Tuple[int, "ob.Ask"]] = None self.sell_rate: Dec = hm.round_decimal(Dec(random.random() / 3 + 0.1)) self.trade_premium: Dec = Dec('0.01') self.trade_duration: int = 10 # step when initialised so nomins appear on the market. self.step()
def lin_sequence_series_dec(n): a = 1 s = Dec(0) for i in range(1, n + 1): s += 1 / Dec(a) print("i: {}, a: {}, s: {}".format(i, a, s)) a = a * 2 + 1 return s
def bbp_term(k): '''Calculates k-th hexademical digit of pi.''' first = Dec('4') / Dec(str(8 * k + 1)) second = Dec('2') / Dec(str(8 * k + 4)) third = Dec('1') / Dec(str(8 * k + 5)) fourth = Dec('1') / Dec(str(8 * k + 6)) return (first - second - third - fourth) / Dec(str(16**k))
def calculate_group_size(_total_count, _infect_rate, _minimum, _maximum): _middle = Dec(_minimum + _maximum) / Dec(2) _middle_middle = Dec(_minimum + _middle) / Dec(2) _middle_expectation = _calculate_expectation(_total_count, _infect_rate, _middle) _middle_middle_expectation = _calculate_expectation(_total_count, _infect_rate, _middle_middle) if np.abs(_middle - _middle_middle) < 0.001: return _middle, _middle_expectation if _middle_expectation > _middle_middle_expectation: _result = calculate_group_size(_total_count, _infect_rate, _middle_middle, _maximum) else: _result = calculate_group_size(_total_count, _infect_rate, _minimum, _middle) return _result
def dec_cos(d, n_max=14): d_1 = Dec(1) s = Dec(1) n = 2 sig = -1 while n <= n_max: s += d**n / factorial(n) * sig n += 2 sig *= -1 return s