def f75(n): s = BigFloat(0) for i in range(1, n + 1): expr = 1 / (1 - 2**BigFloat(-i)) - 1 s += bigchoose(n, i) * 2**i * (-1)**(i + 1) * expr return 1.0 / 2 * s
def calc_ratio(n): l = BigFloat(0) h = BigFloat(1) m = (l + h) * 0.5 def calc_y1(x): return x / n def diff(x): return (calc_y1(x) - (1 - sqrt(1 - (1 - x)**2))) m_d = diff(m) DIFF = BigFloat('1e-20') while abs(m_d) > DIFF: if m_d < 0: l = m else: h = m m = (l + h) * 0.5 m_d = diff(m) x = x1 = m y1 = calc_y1(x) left_area = x1 * y1 * 0.5 right_area = ((y1 + 1) * (1 - x1) * 0.5 - asin(1 - x1) * 0.5) return ((left_area + right_area) / L_sect_area)
def f66(n): s1 = BigFloat(0) for mu in range(1, MAX_MU): s2 = BigFloat(0) for i in range(0, n + 1): s2 += bigchoose(n, i) * (-(2**(1 - mu)))**i s1 += 1 - s2 return 1.0 / 2 * s1
def test_get_f(self): alpha = math.pi / 4 beta = math.pi / 4 a = BigFloat.exact(0.2) b = BigFloat.exact(0.6) wavelength = BigFloat.exact(0.1) f = processor.get_f(alpha, beta, a, b, wavelength) self.assertAlmostEqual(f, 1.002 * 10 ** (-5))
def generate_random_gaussian(cls, n_dimensions, one_vector): mean = np.array([BigFloat.exact("0", precision=110)] * n_dimensions) sigma = np.array([BigFloat.exact("0", precision=110)] * n_dimensions) for i in range(n_dimensions): # TODO: Multivariate normal should accept 0 values, not require just a small value. mean[i] = one_vector.component(i) + random.randint(-100, 100) / 50 # sigma[i][i] = random.randint(100, 1000) / 0.5 sigma[i] = 3e1 return Gaussian(mean, sigma)
def mk_bfc(self, x, y): from bigfloat import BigFloat, precision from mbrat.util import Arguments with precision(self.prec): bf_x = BigFloat.exact(x) bf_y = BigFloat.exact(y) return Arguments( {'real': bf_x, 'imag': bf_y}, string="bfc(real='{0}', imag='{1}')".format(bf_x, bf_y) )
def f69(n): odd_bound = int(math.floor((n - 1) / 2)) even_bound = int(math.floor(n / 2)) s1 = BigFloat(0) for mu in range(1, MAX_MU): s2 = BigFloat(0) for k in range(0, odd_bound + 1): s2 += bigchoose(n, 2 * k + 1) * 2**((1 - mu) * (2 * k + 1)) s3 = BigFloat(0) for k in range(1, even_bound + 1): s3 += bigchoose(n, 2 * k) * 2**((1 - mu) * 2 * k) s1 += s2 - s3 return 1.0 / 2 * s1
def f74(n): odd_bound = int(math.floor((n - 1) / 2)) even_bound = int(math.floor(n / 2)) s10 = BigFloat(0) for k in range(0, odd_bound + 1): s1 = 1 / (1 - 2**(-(2 * BigFloat(k) + 1))) s10 += bigchoose(n, 2 * k + 1) * 2**(2 * k + 1) * (s1 - 1) s20 = BigFloat(0) for k in range(1, even_bound + 1): s2 = 1 / (1 - 2**(-2 * BigFloat(k))) s20 += bigchoose(n, 2 * k) * 2**(2 * k) * (s2 - 1) return 1.0 / 2 * (s10 - s20)
def __json_list_to_numpy_list(self, jsonList): newList = [] for v in iter(jsonList): newList.append( BigFloat.exact(v[Gaussian.__VALUE], precision=v[Gaussian.__PRECISION])) return np.array(newList)
def f76(n): s = BigFloat(0) for i in range(1, n + 1): expr = 2**i / (2**i - 1) s += bigchoose(n, i) * (-1)**(i + 1) * expr return 1.0 / 2 * s
def compute_boltzmann(energies, debug): # create Boltzmann distribution # https://en.wikipedia.org/wiki/Boltzmann_distribution # p_i = exp( -E_i / kT ) / ∑ exp( -E_j / kT ) # where: # p_i is the probability of state i occuring # E_i is the energy of state i # E_j is the energy of state j, where the ∑ in the denominator # iterates over all states j # first we calculate exp( -E_i / kT ) for all states if len(energies) == 0: return [] if debug: print("Boltzmann Distribution") divisor = BigFloat.exact(0.0) for energy in energies: ep = bigfloat.exp(-energy) if debug: print("energy, ep = %g, %g" % (energy, ep)) # divisor = ∑ exp( -E_j / kT ) divisor += ep probabilities = [] for energy in energies: # p_i = exp( -E_i / kT ) / divisor numerator = bigfloat.exp(-energy) probability = numerator / divisor # save probability to dictionary probabilities.append(float(probability)) if debug: print("%s / %s = %s" % (numerator, divisor, probability)) return probabilities
def __super_vectors_mean(svectors, weights): dimensions = svectors[0].dimensions() mean = np.array([BigFloat.exact("0", precision=110)] * dimensions) for i in range(dimensions): for svec_id in range(len(svectors)): mean[i] += svectors[svec_id].component(i) * weights[svec_id] mean[i] /= sum(weights) return mean
def __init__(self, size, cellSize, distance): self.size = np.array(size) self.cellSize = np.array(cellSize).astype(BigFloat) self.distance = BigFloat(distance) # Angle binning of detector self.anglePerCell = [ bf.atan(cellSize / self.distance) for cellSize in self.cellSize ]
def test_empty_format_matches_str(self): test_values = [ BigFloat("0.0"), BigFloat("-0.0"), BigFloat("1.0"), BigFloat("-2.3"), BigFloat("1e100"), BigFloat("1e-100"), BigFloat("nan"), BigFloat("inf"), BigFloat("-inf"), ] for value in test_values: self.assertEqual(str(value), format(value, ""))
def test_empty_format_matches_str(self): test_values = [ BigFloat('0.0'), BigFloat('-0.0'), BigFloat('1.0'), BigFloat('-2.3'), BigFloat('1e100'), BigFloat('1e-100'), BigFloat('nan'), BigFloat('inf'), BigFloat('-inf'), ] for value in test_values: self.assertEqual(str(value), format(value, ''))
def __init__(self, pos, directionAngles): self.pos = np.array(pos) self.directionAngles = np.array(directionAngles).astype(BigFloat) assert (len(directionAngles) == 2) self.dir = np.array([ BigFloat(1), bf.atan(directionAngles[0]), bf.atan(directionAngles[1]) ])
def f73(n): odd_bound = int(math.floor((n - 1) / 2)) even_bound = int(math.floor(n / 2)) s10 = BigFloat(0) for k in range(0, odd_bound + 1): s1 = BigFloat(0) for mu in range(0, MAX_MU): s1 += (2**(2 * k + 1))**(-mu) s10 += bigchoose(n, 2 * k + 1) * 2**(2 * k + 1) * (s1 - 1) s20 = BigFloat(0) for k in range(1, even_bound + 1): s2 = BigFloat(0) for mu in range(0, MAX_MU): s2 += (2**(2 * k))**(-mu) s20 += bigchoose(n, 2 * k) * 2**(2 * k) * (s2 - 1) return 1.0 / 2 * (s10 - s20)
def transform(s, l): with precision(100): ret = [BigFloat(0) for x in xrange(1 + s * (len(l)-1))] prev = [1] for i, v in enumerate(l): if i > 0: f = BigFloat(1) / (BigFloat(s) ** i) new = [BigFloat(0) for x in xrange(1 + s * i)] for faceval in xrange(1, s+1): for idx, val in enumerate(prev): new[idx+faceval] += val if v > 0: for idx, val in enumerate(new): ret[idx] += val * v * f prev = new # while ret[-1] == 0: # ret.pop() print("s = ", s, " ; ret = ", ["%f" % x for x in ret]) sys.stdout.flush() return [x/sum(ret) for x in ret]
def calcPhase(particle, detector, sim, waveLen): """Calculate the phase the particle has at the detector (current phase assumed to be 0)""" detCellIdx = getBinnedDetCellIdx(particle, detector, sim) #print("Target angles:", (detCellIdx - detector.size / 2) * detector.anglePerCell) dx = detector.distance + (sim.size[0] - particle.pos[0]) * sim.cellSize[0] dzdy = (detCellIdx - detector.size / 2) * detector.cellSize dydz = np.flipud(dzdy) + (sim.size[1:] / 2 - particle.pos[1:]) * sim.cellSize[1:] distance = bf.sqrt(dx**2 + dydz[0]**2 + dydz[1]**2) phase = 2 * bf.const_pi() / BigFloat(waveLen) * distance phase = bf.mod(phase, 2 * bf.const_pi()) return phase
def __probabilities_to_weights(probabilities): weights = [] sums = np.array([BigFloat.exact("0", precision=110)] * len(probabilities[0])) for p in iter(probabilities): weights.append(np.array(p)) sums += weights[len(weights) - 1] for i in range(len(weights)): weights[i] /= sums return weights
def __super_vectors_sigma(svectors, mean, weights): dimensions = svectors[0].dimensions() values_from_dimensions = __supervectors_to_array_of_values_for_each_dimension( svectors) sigma = np.array([BigFloat.exact("0", precision=110)] * dimensions) for i in range(dimensions): sigma[i] = __weighted_variance(mean[i], values_from_dimensions[i], weights) # if math.isclose(sigma[i], 0, abs_tol=3.0e-20): # print(sigma[i][i]) # raise NoVarianceException # sigma[i] = 3.0e-20 return sigma
def calcPhaseFarField(particle, sim, waveLen): """Calculate the phase the particle has at the detector in the far field""" # Only scatter in 1 direction assert (particle.directionAngles[0] == 0 or particle.directionAngles[1] == 0) # One of the sin is 0 -> Ok to use addition instead of a full projection pathDiff = particle.pos[1] * sim.cellSize[1] * bf.sin(particle.directionAngles[0]) + \ particle.pos[2] * sim.cellSize[2] * bf.sin(particle.directionAngles[1]) # Negate as increasing position decreases phase pathDiff = -pathDiff phase = 2 * bf.const_pi() / BigFloat(waveLen) * pathDiff phase = bf.mod(phase, 2 * bf.const_pi()) return phase
def invert(lower: BigFloat, upper: BigFloat, precision_of_result: int) -> ExactRealProgram: context_down = bf.precision(precision_of_result) + bf.RoundTowardNegative context_up = bf.precision(precision_of_result) + bf.RoundTowardPositive # interval doesn't contain zero then invert and flip [1 / y2, 1 / y1] if (lower > 0 and upper > 0) or (lower < 0 and upper < 0): inv_lower = bf.div(1, upper, context_down) inv_upper = bf.div(1, lower, context_up) lw = [0, -float(inv_upper)**2] uw = [-float(inv_lower)**2, 0] # [lower, 0] -> [-infty, 1 / y1] elif lower < 0 and upper == 0: inv_lower = BigFloat('-inf') inv_upper = bf.div(1, lower, context_up) lw = [0, float('nan')] uw = [-float(inv_lower)**2, 0] # [0, upper] -> [1 / y2, infty] elif lower == 0 and upper > 0: inv_lower = bf.div(1, upper, context_down) inv_upper = BigFloat('inf') lw = [0, -float(inv_upper)**2] uw = [float('nan'), 0] # If the interval includes 0 just give up and return [-infty, infty] # Note: an alternative is to split up intervals, but that's too tricky for now elif lower < 0 < upper: inv_lower = BigFloat('-inf') inv_upper = BigFloat('inf') lw = [0, float('nan')] uw = [float('nan'), 0] # Interval is probably such that lower is greater than upper else: raise ValueError("Input interval is invalid for division") return inv_lower, inv_upper, lw, uw
def transform_brute(s, l): with precision(100): ret = [BigFloat(0) for x in xrange(1 + s * (len(l)-1))] for i, v in enumerate(l): if i == 0: continue def rec(sum_, c): if i == c: ret[sum_] += BigFloat(v)/(BigFloat(s)**i) else: for x in xrange(1, s+1): rec(sum_+x, c+1) rec(0, 0) return [x/sum(ret) for x in ret]
def test_invalid_formats(self): invalid_formats = [ # Can't specify fill/align *and* zero padding at once ... "X<010.2f", ">010.2f", " ^010.2f", "=010.2f", # ... even if the fill/align matches the zero padding! "0=010.2f", # a . must be followed by a precision. ".f", "10.g", ] for fmt in invalid_formats: with self.assertRaises(ValueError): format(BigFloat(2), fmt)
def calc_variance_brute(x12): s = 20 with precision(100): s_sq = [0, 0, 0] for i, v in enumerate(x12): if i > 0: f = BigFloat(1) / (BigFloat(s) ** i) print("i = ", i) def rec(s_sq, sum_, c): if (c == i): s_sq[0] += f * v * sum_ * sum_ s_sq[1] += f * v * sum_ s_sq[2] += f * v else: for x in xrange(1, 21): rec(s_sq, sum_+x, c+1) rec(s_sq, 0, 0) print("s_sq = ", s_sq) return (BigFloat(s_sq[0])/BigFloat(s_sq[2]) - ((BigFloat(s_sq[1])/BigFloat(s_sq[2]))**2))
def test_format(self): # Fixed precision formatting. test_triples = [ (BigFloat(2), ".6f", "2.000000"), # 'F' behaves the same as 'f' except for infinities and nans. (BigFloat(2), ".6F", "2.000000"), # Extra zeros in the precision should be fine. (BigFloat(2), ".06f", "2.000000"), (BigFloat(2), ".5f", "2.00000"), # . only retained with 'alternate' formatting (BigFloat(2), ".0f", "2"), # Default precision is 6. (BigFloat(2), "f", "2.000000"), (BigFloat('nan'), "f", "nan"), (BigFloat('-nan'), "f", "nan"), (BigFloat('inf'), "f", "inf"), (BigFloat('-inf'), "f", "-inf"), (BigFloat('nan'), "F", "NAN"), (BigFloat('-nan'), "F", "NAN"), (BigFloat('inf'), "F", "INF"), (BigFloat('-inf'), "F", "-INF"), # Rounding behaviour. (BigFloat('3.1415926535'), ".6f", "3.141593"), (BigFloat('3.1415926535'), ".5f", "3.14159"), (BigFloat('3.1415926535'), ".4f", "3.1416"), (BigFloat('3.1415926535'), ".3f", "3.142"), (BigFloat('3.1415926535'), ".2f", "3.14"), (BigFloat('3.1415926535'), ".1f", "3.1"), (BigFloat('3.1415926535'), ".0f", "3"), # Sign specification. (BigFloat(+2), "+.3f", "+2.000"), (BigFloat(-2), "+.3f", "-2.000"), (BigFloat(+2), " .3f", " 2.000"), (BigFloat(-2), " .3f", "-2.000"), (BigFloat(+2), "-.3f", "2.000"), (BigFloat(-2), "-.3f", "-2.000"), (BigFloat(+2), ".3f", "2.000"), (BigFloat(-2), ".3f", "-2.000"), # With infinities and nans; note that MPFR doesn't include # these signs. (BigFloat('+inf'), "+.3f", "+inf"), (BigFloat('-inf'), "+.3f", "-inf"), (BigFloat('+nan'), "+.3f", "+nan"), (BigFloat('+inf'), "-.3f", "inf"), (BigFloat('-inf'), "-.3f", "-inf"), (BigFloat('+nan'), "-.3f", "nan"), (BigFloat('+inf'), " .3f", " inf"), (BigFloat('-inf'), " .3f", "-inf"), (BigFloat('+nan'), " .3f", " nan"), # Alternate formatting. (BigFloat(2), "#.0f", "2."), (BigFloat(2), "+#.0f", "+2."), # Minimum field width. (BigFloat(2), "10.3f", " 2.000"), (BigFloat(2), "6.3f", " 2.000"), (BigFloat(2), "5.3f", "2.000"), (BigFloat(2), "4.3f", "2.000"), (BigFloat(2), "1.3f", "2.000"), # Minimum field width in combination with sign. (BigFloat(2), "+10.3f", " +2.000"), (BigFloat(-23), "+10.3f", " -23.000"), # Zero padding. (BigFloat(2), "010.3f", "000002.000"), (BigFloat(2), "+010.3f", "+00002.000"), (BigFloat(2), " 010.3f", " 00002.000"), (BigFloat(2), "0010.3f", "000002.000"), # Alignment and filling. (BigFloat(2), "<10.3f", "2.000 "), (BigFloat(2), ">10.3f", " 2.000"), (BigFloat(2), "^10.3f", " 2.000 "), (BigFloat(2), "<10.2f", "2.00 "), (BigFloat(2), ">10.2f", " 2.00"), (BigFloat(2), "^10.2f", " 2.00 "), (BigFloat(2), "<4.2f", "2.00"), (BigFloat(2), ">4.2f", "2.00"), (BigFloat(2), "^4.2f", "2.00"), (BigFloat(2), "<3.2f", "2.00"), (BigFloat(2), ">3.2f", "2.00"), (BigFloat(2), "^3.2f", "2.00"), (BigFloat(2), "X<10.3f", "2.000XXXXX"), (BigFloat(2), "X>10.3f", "XXXXX2.000"), (BigFloat(2), "X^10.3f", "XX2.000XXX"), (BigFloat(2), "X<10.2f", "2.00XXXXXX"), (BigFloat(2), "X>10.2f", "XXXXXX2.00"), (BigFloat(2), "X^10.2f", "XXX2.00XXX"), (BigFloat(2), "X<4.2f", "2.00"), (BigFloat(2), "X>4.2f", "2.00"), (BigFloat(2), "X^4.2f", "2.00"), (BigFloat(2), "X<3.2f", "2.00"), (BigFloat(2), "X>3.2f", "2.00"), (BigFloat(2), "X^3.2f", "2.00"), (BigFloat(2), "X=+10.3f", "+XXXX2.000"), (BigFloat(2), " =+10.3f", "+ 2.000"), (BigFloat(2), "0=+10.3f", "+00002.000"), (BigFloat(2), "\x00=+10.3f", "+\x00\x00\x00\x002.000"), (BigFloat(2), "\n=+10.3f", "+\n\n\n\n2.000"), # e-style formatting (BigFloat(2), ".6e", "2.000000e+00"), (BigFloat(3.141592653589793), ".6e", "3.141593e+00"), (BigFloat(3.141592653589793), ".6E", "3.141593E+00"), (BigFloat(314.1592653589793), ".6e", "3.141593e+02"), (BigFloat(314.1592653589793), ".6E", "3.141593E+02"), (BigFloat('nan'), "e", "nan"), (BigFloat('-nan'), "e", "nan"), (BigFloat('inf'), "e", "inf"), (BigFloat('-inf'), "e", "-inf"), (BigFloat('nan'), "E", "NAN"), (BigFloat('-nan'), "E", "NAN"), (BigFloat('inf'), "E", "INF"), (BigFloat('-inf'), "E", "-INF"), (BigFloat(314.1592653589793), ".0e", "3e+02"), (BigFloat(314.1592653589793), "#.0e", "3.e+02"), (BigFloat(314.1592653589793), "e", "3.1415926535897933e+02"), (BigFloat(314.1592653589793), "6e", "3.1415926535897933e+02"), # g-style formatting (BigFloat(3.141592653589793), ".7g", "3.141593"), (BigFloat(3.141592653589793), ".7G", "3.141593"), (BigFloat(314.1592653589793), ".7g", "314.1593"), (BigFloat(31415.92653589793), ".7g", "31415.93"), (BigFloat(3141592.653589793), ".7g", "3141593"), (BigFloat(3141592.653589793), ".7G", "3141593"), (BigFloat(31415926.53589793), ".7g", "3.141593e+07"), (BigFloat(31415926.53589793), ".7G", "3.141593E+07"), (BigFloat('nan'), "g", "nan"), (BigFloat('-nan'), "g", "nan"), (BigFloat('inf'), "g", "inf"), (BigFloat('-inf'), "g", "-inf"), (BigFloat('nan'), "G", "NAN"), (BigFloat('-nan'), "G", "NAN"), (BigFloat('inf'), "G", "INF"), (BigFloat('-inf'), "G", "-INF"), (BigFloat(314.1592653589793), ".0g", "3e+02"), (BigFloat(314.1592653589793), ".1g", "3e+02"), (BigFloat(314.1592653589793), "#.0g", "3.e+02"), (BigFloat(314.1592653589793), "#.1g", "3.e+02"), (BigFloat(314.1592653589793), "g", "314.159"), (BigFloat(314.1592653589793), "6g", "314.159"), # Trailing zeros are stripped, except in alternate style. (BigFloat(2), ".6g", "2"), (BigFloat(0.000023), ".6g", "2.3e-05"), (BigFloat(0.00023), ".6g", "0.00023"), (BigFloat(2.3), ".6g", "2.3"), (BigFloat(230), ".6g", "230"), (BigFloat(230000), ".6g", "230000"), (BigFloat(2300000), ".6g", "2.3e+06"), (BigFloat(2), "#.6g", "2.00000"), # %-formatting (BigFloat(3.141592653589793), ".2%", "314.16%"), (BigFloat(3.141592653589793), ".1%", "314.2%"), (BigFloat(3.141592653589793), ".0%", "314%"), (BigFloat(3.141592653589793), "%", "314.159265%"), (BigFloat(0.0234), ".3%", "2.340%"), (BigFloat(0.00234), ".3%", "0.234%"), (BigFloat(0.000234), ".3%", "0.023%"), (BigFloat(0.000234), ".3U%", "0.024%"), (BigFloat(0.0000234), ".3%", "0.002%"), (BigFloat(0.00000234), ".3%", "0.000%"), (BigFloat(0.00000234), ".3Y%", "0.001%"), (BigFloat(-3.141592653589793), ".2%", "-314.16%"), (BigFloat(-3.141592653589793), ".1%", "-314.2%"), (BigFloat(-3.141592653589793), ".0%", "-314%"), (BigFloat(-3.141592653589793), "%", "-314.159265%"), (BigFloat(-0.0234), ".3%", "-2.340%"), (BigFloat(-0.00234), ".3%", "-0.234%"), (BigFloat(-0.000234), ".3%", "-0.023%"), (BigFloat(-0.000234), ".3U%", "-0.023%"), (BigFloat(-0.0000234), ".3%", "-0.002%"), (BigFloat(-0.00000234), ".3%", "-0.000%"), (BigFloat(-0.00000234), ".3Y%", "-0.001%"), (BigFloat('0'), ".3%", "0.000%"), (BigFloat('-0'), ".3%", "-0.000%"), # We should see the '%' even on infinities and nans. (BigFloat('inf'), ".3%", "inf%"), (BigFloat('-inf'), ".3%", "-inf%"), (BigFloat('nan'), ".3%", "nan%"), (BigFloat('inf'), "+.3%", "+inf%"), (BigFloat('-inf'), "+.3%", "-inf%"), (BigFloat('nan'), "+.3%", "+nan%"), # Hexadecimal formatting. It's not 100% clear how MPFR # chooses the exponent here. (BigFloat(1.5), ".6a", "0x1.800000p+0"), (BigFloat(1.5), ".5a", "0x1.80000p+0"), (BigFloat(1.5), ".1a", "0x1.8p+0"), (BigFloat(1.5), ".0a", "0xcp-3"), (BigFloat(1.5), ".6A", "0X1.800000P+0"), (BigFloat(3.0), ".6a", "0x3.000000p+0"), (BigFloat(3.141592653589793), ".6a", "0x3.243f6bp+0"), (BigFloat(3.141592653589793), ".5a", "0x3.243f7p+0"), (BigFloat(3.141592653589793), ".4a", "0x3.243fp+0"), (BigFloat(3.141592653589793), ".3a", "0x3.244p+0"), (BigFloat(3.141592653589793), ".2a", "0x3.24p+0"), (BigFloat(3.141592653589793), ".1a", "0x3.2p+0"), (BigFloat(3.141592653589793), ".0a", "0xdp-2"), # With no precision, outputs enough digits to give an # exact representation. (BigFloat(3.141592653589793), "a", "0x3.243f6a8885a3p+0"), (BigFloat(10.0), ".6a", "0xa.000000p+0"), (BigFloat(16.0), ".6a", "0x1.000000p+4"), (BigFloat('nan'), "a", "nan"), (BigFloat('-nan'), "a", "nan"), (BigFloat('inf'), "a", "inf"), (BigFloat('-inf'), "a", "-inf"), (BigFloat('nan'), "A", "NAN"), (BigFloat('-nan'), "A", "NAN"), (BigFloat('inf'), "A", "INF"), (BigFloat('-inf'), "A", "-INF"), # Binary formatting. (BigFloat('2.25'), "b", '1.001p+1'), (BigFloat('-2.25'), "b", '-1.001p+1'), (BigFloat('nan'), "b", 'nan'), (BigFloat('inf'), "b", "inf"), (BigFloat('-inf'), "b", "-inf"), # Rounding mode. # Round up. (BigFloat('-56.127'), ".2Uf", "-56.12"), (BigFloat('-56.125'), ".2Uf", "-56.12"), (BigFloat('-56.123'), ".2Uf", "-56.12"), (BigFloat('56.123'), ".2Uf", "56.13"), (BigFloat('56.125'), ".2Uf", "56.13"), (BigFloat('56.127'), ".2Uf", "56.13"), # Round down. (BigFloat('-56.127'), ".2Df", "-56.13"), (BigFloat('-56.125'), ".2Df", "-56.13"), (BigFloat('-56.123'), ".2Df", "-56.13"), (BigFloat('56.123'), ".2Df", "56.12"), (BigFloat('56.125'), ".2Df", "56.12"), (BigFloat('56.127'), ".2Df", "56.12"), # Round away from zero. (BigFloat('-56.127'), ".2Yf", "-56.13"), (BigFloat('-56.125'), ".2Yf", "-56.13"), (BigFloat('-56.123'), ".2Yf", "-56.13"), (BigFloat('56.123'), ".2Yf", "56.13"), (BigFloat('56.125'), ".2Yf", "56.13"), (BigFloat('56.127'), ".2Yf", "56.13"), # Round toward zero. (BigFloat('-56.127'), ".2Zf", "-56.12"), (BigFloat('-56.125'), ".2Zf", "-56.12"), (BigFloat('-56.123'), ".2Zf", "-56.12"), (BigFloat('56.123'), ".2Zf", "56.12"), (BigFloat('56.125'), ".2Zf", "56.12"), (BigFloat('56.127'), ".2Zf", "56.12"), # Round to nearest (ties to even). (BigFloat('-56.127'), ".2Nf", "-56.13"), (BigFloat('-56.125'), ".2Nf", "-56.12"), (BigFloat('-56.123'), ".2Nf", "-56.12"), (BigFloat('56.123'), ".2Nf", "56.12"), (BigFloat('56.125'), ".2Nf", "56.12"), (BigFloat('56.127'), ".2Nf", "56.13"), # Missing rounding mode implies round to nearest. (BigFloat('-56.127'), ".2f", "-56.13"), (BigFloat('-56.125'), ".2f", "-56.12"), (BigFloat('-56.123'), ".2f", "-56.12"), (BigFloat('56.123'), ".2f", "56.12"), (BigFloat('56.125'), ".2f", "56.12"), (BigFloat('56.127'), ".2f", "56.13"), # Missing type behaves like str formatting. (BigFloat('123'), ".0", "1e+02"), (BigFloat('123'), ".1", "1e+02"), (BigFloat('123'), ".2", "1.2e+02"), (BigFloat('123'), ".2U", "1.3e+02"), (BigFloat('123'), ".2D", "1.2e+02"), (BigFloat('123'), ".3", "123"), # 'alternate' flag is currently ignored. (BigFloat('123'), "#.3", "123"), (BigFloat('123'), ".4", "123.0"), (BigFloat('123'), "#.4", "123.0"), (BigFloat('123'), ".0", "1e+02"), (BigFloat('123'), "", "123.00000000000000"), (BigFloat('nan'), "", "nan"), (BigFloat('inf'), "", "inf"), (BigFloat('-inf'), "", "-inf"), ] for bf, fmt, expected_output in test_triples: result = format(bf, fmt) self.assertEqual(result, expected_output, msg=(bf, fmt, expected_output))
#!/usr/bin/env python import sys import math from bigfloat import BigFloat, precision if sys.version_info > (3, ): long = int xrange = range with precision(20000): N_tosses = 1000 h_probs = [ math.factorial(N_tosses) / (math.factorial(x) * math.factorial(N_tosses - x)) * (BigFloat('0.5')**N_tosses) for x in xrange(N_tosses + 1) ] s = 0 h_sums = [0] for x in h_probs: s += x h_sums.append(s + 0) def calc_prob(f, h_sums): h = N_tosses + 0 money = (1 + 2 * f)**h while money > 1e9: h -= 1 money *= (1 - f) / (1 + 2 * f) h += 1 return h
def main(): assert_ratio(1, 0.5, 1e-8) assert_ratio(2, BigFloat(36.46) / 100, 1e-2) assert_ratio(15, 0.1, 1e-2) print_less_than(0.1) print_less_than(BigFloat('1e-3'))
self.a = self.b = None def __iter__(self): for value in self.values(): self.a, self.b = self.b, value yield value def values(self): yield Fraction(2, 1) yield Fraction(-4, 1) while True: def f(y, z): a = Fraction(111, 1) b = Fraction(1130, 1) / y c = Fraction(3000, 1) / (z * y) return a - b + c yield f(self.b, self.a) print(list(take(10, JMM()))) with precision(9000): for a, b in zip(forever(0), JMM()): fnumerator = BigFloat(b.numerator) fdenominator = BigFloat(b.denominator) big = fnumerator / fdenominator strbig = str(big)[:140] print(f"{a:>5}: {strbig} {b}")
def rec(sum_, c): if i == c: ret[sum_] += BigFloat(v)/(BigFloat(s)**i) else: for x in xrange(1, s+1): rec(sum_+x, c+1)
def __init__(self, constant: float): context_down = bf.precision(53) + bf.RoundTowardNegative context_up = bf.precision(53) + bf.RoundTowardPositive super(ExactConstant, self).__init__([], BigFloat(constant, context_down), BigFloat(constant, context_up))
import sys from bigfloat import precision, BigFloat, const_pi, sqrt, asin if sys.version_info > (3, ): long = int with precision(100): L_sect_area = (1 - BigFloat(const_pi()) / 4) def calc_ratio(n): l = BigFloat(0) h = BigFloat(1) m = (l + h) * 0.5 def calc_y1(x): return x / n def diff(x): return (calc_y1(x) - (1 - sqrt(1 - (1 - x)**2))) m_d = diff(m) DIFF = BigFloat('1e-20') while abs(m_d) > DIFF: if m_d < 0: l = m else: h = m m = (l + h) * 0.5 m_d = diff(m) x = x1 = m y1 = calc_y1(x)