def frexp(x): """ Version of frexp that works for numbers with uncertainty, and also for regular numbers. """ # The code below is inspired by uncert_core.wrap(). It is # simpler because only 1 argument is given, and there is no # delegation to other functions involved (as for __mul__, etc.). aff_func = to_affine_scalar(x) if aff_func._linear_part: (mantissa, exponent) = math.frexp(aff_func.nominal_value) return ( AffineScalarFunc( mantissa, # With frexp(x) = (m, e), x = m*2**e, so m = x*2**-e # and therefore dm/dx = 2**-e (as e in an integer that # does not vary when x changes): LinearCombination([2**-exponent, aff_func._linear_part])), # The exponent is an integer and is supposed to be # continuous (errors must be small): exponent) else: # This function was not called with an AffineScalarFunc # argument: there is no need to return numbers with uncertainties: return math.frexp(x)
def rebin(self, x_rebin_fact, y_rebin_fact): """ Rebin the data and adjust dims """ if self.data == None: raise Exception('Please read in the file you wish to rebin first') (mantis_x, exp_x) = math.frexp(x_rebin_fact) (mantis_y, exp_y) = math.frexp(y_rebin_fact) # FIXME - this is a floating point comparison, is it always exact? if (mantis_x != 0.5 or mantis_y != 0.5): raise Exception('Rebin factors not power of 2 not supported (yet)') if int(self.dim1 / x_rebin_fact) * x_rebin_fact != self.dim1 or \ int(self.dim2 / x_rebin_fact) * x_rebin_fact != self.dim2 : raise('image size is not divisible by rebin factor - ' + \ 'skipping rebin') pass ## self.data.savespace(1) # avoid the upcasting behaviour i = 1 while i < x_rebin_fact: # FIXME - why do you divide by 2? Rebinning should increase counts? self.data = ((self.data[:, ::2] + self.data[:, 1::2]) / 2) i = i * 2 i = 1 while i < y_rebin_fact: self.data = ((self.data[::2, :] + self.data[1::2, :]) / 2) i = i * 2 self.resetvals() self.dim1 = self.dim1 / x_rebin_fact self.dim2 = self.dim2 / y_rebin_fact #update header self.update_header()
def frexp(x): """ Version of frexp that works for numbers with uncertainty, and also for regular numbers. """ # The code below is inspired by uncertainties.wrap(). It is # simpler because only 1 argument is given, and there is no # delegation to other functions involved (as for __mul__, etc.). aff_func = to_affine_scalar(x) if aff_func.derivatives: result = math.frexp(aff_func.nominal_value) # With frexp(x) = (m, e), dm/dx = 1/(2**e): factor = 1/(2**result[1]) return ( AffineScalarFunc( result[0], # Chain rule: dict([(var, factor*deriv) for (var, deriv) in aff_func.derivatives.iteritems()])), # The exponent is an integer and is supposed to be # continuous (small errors): result[1]) else: # This function was not called with an AffineScalarFunc # argument: there is no need to return numbers with uncertainties: return math.frexp(x)
def _product(values): """Return product of values as (exponent, mantissa).""" errmsg = 'mixed Decimal and float is not supported' prod = 1 for x in values: if isinstance(x, float): break prod *= x else: return (0, prod) if isinstance(prod, Decimal): raise TypeError(errmsg) # Since floats can overflow easily, we calculate the product as a # sort of poor-man's BigFloat. Given that: # # x = 2**p * m # p == power or exponent (scale), m = mantissa # # we can calculate the product of two (or more) x values as: # # x1*x2 = 2**p1*m1 * 2**p2*m2 = 2**(p1+p2)*(m1*m2) # mant, scale = 1, 0 #math.frexp(prod) # FIXME for y in chain([x], values): if isinstance(y, Decimal): raise TypeError(errmsg) m1, e1 = math.frexp(y) m2, e2 = math.frexp(mant) scale += (e1 + e2) mant = m1*m2 return (scale, mant)
def nearly_equal(float1, float2, places=15): """ Determines whether two floating point numbers are nearly equal (to within reasonable rounding errors """ mantissa1, exp1 = math.frexp(float1) mantissa2, exp2 = math.frexp(float2) return (round(mantissa1, places) == round(mantissa2, places) and exp1 == exp2)
def __init__(self, L): self.L = L if math.frexp(self.L)[0]!=0.5: print "profile size is not a power of 2" pdb.set_trace() self.J = math.frexp(self.L)[1]-1 self.data = False self.value = dict()
def _not_nearly_equal(self, float1, float2): """ Determines whether two floating point numbers are nearly equal (to within reasonable rounding errors """ mantissa1, exp1 = math.frexp(float1) mantissa2, exp2 = math.frexp(float2) return not ((round(mantissa1, self.nearly_equal_places) == round(mantissa2, self.nearly_equal_places)) and exp1 == exp2)
def SetFog(self,fog): projection = (fog.function >> 3) & 1 if projection: if fog.z_far == fog.z_near or fog.z_end == fog.z_start: A = 0 C = 0 else: A = (fog.z_far - fog.z_near)/(fog.z_end - fog.z_start) C = (fog.z_start - fog.z_near)/(fog.z_end - fog.z_start) b_shift = 0 b_magnitude = 0 else: if fog.z_far == fog.z_near or fog.z_end == fog.z_start: A = 0 B = 0.5 C = 0 else: A = fog.z_far*fog.z_near/((fog.z_far - fog.z_near)*(fog.z_end - fog.z_start)) B = fog.z_far/(fog.z_far - fog.z_near) C = fog.z_start/(fog.z_end - fog.z_start) if B > 1: b_shift = 1 + int(ceil(log(B,2))) elif 0 < B < 0.5: b_shift = 0 else: b_shift = 1 A /= 2**b_shift b_magnitude = int(2*(B/2**b_shift)*8388638) a_mantissa,a_exponent = frexp(A) self.fog_param0[0:11] = int(abs(a_mantissa)*2**12) & 0x7FF self.fog_param0[11:19] = a_exponent + 126 if A != 0 else 0 self.fog_param0[19] = a_mantissa < 0 self.fog_param1[0:24] = b_magnitude self.fog_param2[0:5] = b_shift c_mantissa,c_exponent = frexp(C) self.fog_param3[0:11] = int(abs(c_mantissa)*2**12) & 0x7FF self.fog_param3[11:19] = c_exponent + 126 if C != 0 else 0 self.fog_param3[19] = c_mantissa < 0 self.fog_param3[20:21] = projection self.fog_param3[21:24] = fog.function self.fog_color[0:8] = fog.color.b self.fog_color[8:16] = fog.color.g self.fog_color[16:24] = fog.color.r
def __new__(cls, *args): if len(args) == 0: self = bytes.__new__(cls) self._pad = 0 elif len(args) == 1: if isinstance(args[0], IntType): self = bytes.__new__(cls, uitob(args[0])) else: self = bytes.__new__(cls, args[0]) self._pad = 0 elif len(args) == 2: if isinstance(args[0], str): arg = int(args[0], args[1]) m, e = math.frexp(args[1]) bpd = e - (1 if m == 0.5 else 0) bitlen = len(args[0]) * bpd # num digits * bits per digit shift = ((bitlen + 7) & ~7) - bitlen self = bytes.__new__(cls, uitob(arg << shift)) self._pad = shift & 7 else: self = bytes.__new__(cls, args[1]) self._pad = args[0] if pad > 7 or (pad and not self): raise ValueError('invalid pad value') else: raise TypeError('BitString constructor takes 1 or 2 args') return self
def test_builtin_math_frexp(self): import math def fn(f): return math.frexp(f) res = self.interpret(fn, [10/3.0]) mantissa, exponent = math.frexp(10/3.0) assert self.float_eq(res.item0, mantissa) and self.float_eq(res.item1, exponent)
def log2(x): # Uses an algorithm that should: # (a) produce exact results for powers of 2, and # (b) be monotonic, assuming that the system log is monotonic. if not isfinite(x): if isnan(x): return x # log2(nan) = nan elif x > 0.0: return x # log2(+inf) = +inf else: # log2(-inf) = nan, invalid-operation raise ValueError("math domain error") if x > 0.0: if 0: # HAVE_LOG2 return math.log2(x) m, e = math.frexp(x) # We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when # x is just greater than 1.0: in that case e is 1, log(m) is negative, # and we get significant cancellation error from the addition of # log(m) / log(2) to e. The slight rewrite of the expression below # avoids this problem. if x >= 1.0: return math.log(2.0 * m) / math.log(2.0) + (e - 1) else: return math.log(m) / math.log(2.0) + e else: raise ValueError("math domain error")
def evaluate_func(next_func): if next_func[0] == 'x': return x elif next_func[0] == 'y': return y elif next_func[0] == 'abs': return abs(evaluate_func(next_func[1])) elif next_func[0] == 'cos_pi': return cos(pi*evaluate_func(next_func[1])) elif next_func[0] == 'sin_pi': return sin(pi*evaluate_func(next_func[1])) elif next_func[0] == 'sqrt': return sqrt(abs(pi*evaluate_func(next_func[1]))) elif next_func[0] == 'diff': return evaluate_func(next_func[1])-evaluate_func(next_func[2]) elif next_func[0] == 'ave': return (evaluate_func(next_func[1])+evaluate_func(next_func[2]))/2.0 elif next_func[0] == 'prod': return evaluate_func(next_func[1])*evaluate_func(next_func[2]) elif next_func[0] == 'frexp': return frexp(evaluate_func(next_func[1]))[0] elif next_func[0] == 'x': return evaluate_func(next_func[1]) elif next_func[0] == 'y': return evaluate_func(next_func[2])
def rank_sum_n_sites(measurements, details=False): if math.frexp(len(measurements))[0] != 0.5: print("rank_sum_n_sites received an input of length %s, which is not equal to the number of genotypes." "Quitting." % len(measurements)) sys.exit() output_indices = [] for genotype in measurements: output_indices.append(measurements.keys().index(genotype)) done = False while not done: done = True for i in range(len(measurements) - 1): if ranksums(measurements[measurements.keys()[output_indices[i]]], measurements[measurements.keys()[output_indices[i+1]]])[0] < 0: output_indices[i], output_indices[i + 1] = output_indices[i + 1], output_indices[i] done = False output = [] output_look_good = [] number_loci = 0 for index in output_indices: output.append(measurements.keys()[index]) if len(measurements.keys()[index]) > number_loci: number_loci = len(measurements.keys()[index]) for index in output_indices: output_look_good.append(genotype_look_good(measurements.keys()[index], number_loci)) output_detailed = [] for genotype in output: fitness = measurements[genotype][1:] output_detailed.append([genotype, np.mean(fitness)]) if not details: return output else: return output_detailed
def R4_IEEE2VAX(fpValue, varName): # type: (float, str) -> bytes """ Convert floating point value to VAR REAL*4 string """ try: m, e = math.frexp(float(fpValue)) if m == 0.0: intValue = 0 else: sign = m < 0 exp = e + 128 mant = int((0x1000000 * (abs(m) - 0.5)) + 0.5) while mant >= 0x800000: exp += 1 mant = (mant>> 1) - 0x400000 if exp < 1: intValue = 0 elif exp > 0xff: raise Exception("Exponent too large to store as VAX F float for %s." % varName) else: intValue = ((sign << 15) | (exp << 7) | ((mant & 0x007f0000) >> 16) | ((mant & 0x0000ffff) << 16)) return int_to_bytes(intValue) except: print("VAX float F conversion error for %s value: %s" % (varName, fpValue)) return b"\0\0\0\0"
def float_to_decimal(f): "Convert a floating point number to a Decimal with no loss of information" # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an # exponent. Double the mantissa until it is an integer. Use the integer # mantissa and exponent to compute an equivalent Decimal. If this cannot # be done exactly, then retry with more precision. try: mantissa, exponent = math.frexp(f) except OverflowError: return decimal.Inf while mantissa != int(mantissa): mantissa *= 2.0 exponent -= 1 mantissa = int(mantissa) oldcontext = decimal.getcontext() decimal.setcontext(decimal.Context(traps=[decimal.Inexact])) try: while True: try: return mantissa * decimal.Decimal(2) ** exponent except decimal.Inexact: decimal.getcontext().prec += 1 finally: decimal.setcontext(oldcontext)
def __call__(self, x): if x == 0: return 0, self.mink import math m, e = math.frexp(x) k = max((e - self.bits, self.mink)) return int(m * 2 ** (e - k)), k
def encode_double(value): assert isinstance(value, float) abs_val = _math.fabs(value) # Work around repr()'s propensity to use exponential format # for doubles with really large or really small absolute values. # This extra work is because XML-RPC explicitly DOES NOT support # exponential format, just decimal digits separated by a single # period. if value and (abs_val < 0.0001): # Scary magic for small numbers, split the float into it's # mantissa and exponent components and use the exponent to # guess reasonable format. m, e = _math.frexp(abs_val) decimal_places = int(e/-3) + 17 # Derived at by pure, old-fashon, # trail and error. if decimal_places > 109: # "%.110f" causes an OverflowError. min_value = "0." + "0"*108 + "1" if abs_val < eval(min_value): value = min_value else: value = "%1.109f" % value value = value.rstrip('0') else: value = "%1.*f" % (decimal_places, value) value = value.rstrip('0') elif value and (abs_val > 99999999999999984.0): value = "%.1f" % value else: value = repr(value) return "<value><double>" + value + "</double></value>\n"
def _hash_float(space, v): if not isfinite(v): if isinf(v): return HASH_INF if v > 0 else -HASH_INF return HASH_NAN m, e = math.frexp(v) sign = 1 if m < 0: sign = -1 m = -m # process 28 bits at a time; this should work well both for binary # and hexadecimal floating point. x = r_uint(0) while m: x = ((x << 28) & HASH_MODULUS) | x >> (HASH_BITS - 28) m *= 268435456.0 # 2**28 e -= 28 y = r_uint(m) # pull out integer part m -= y x += y if x >= HASH_MODULUS: x -= HASH_MODULUS # adjust for the exponent; first reduce it modulo HASH_BITS e = e % HASH_BITS if e >= 0 else HASH_BITS - 1 - ((-1 - e) % HASH_BITS) x = ((x << e) & HASH_MODULUS) | x >> (HASH_BITS - e) x = intmask(intmask(x) * sign) return -2 if x == -1 else x
def float2decimal(fval): """ Convert a floating point number to a Decimal with no loss of information """ # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an # exponent. Double the mantissa until it is an integer. Use the integer # mantissa and exponent to compute an equivalent Decimal. If this cannot # be done exactly, then retry with more precision. # # This routine is from # http://docs.python.org/release/2.5.2/lib/decimal-faq.html mantissa, exponent = math.frexp(fval) try: while mantissa != int(mantissa): mantissa *= 2.0 exponent -= 1 mantissa = int(mantissa) except (OverflowError, ValueError): return "---" oldcontext = decimal.getcontext() decimal.setcontext(decimal.Context(traps=[decimal.Inexact])) try: while True: try: return mantissa * decimal.Decimal(2) ** exponent except decimal.Inexact: decimal.getcontext().prec += 1 finally: decimal.setcontext(oldcontext)
def naturallog(x): mantissa , exponent = math.frexp(x) ln2 = 0.693147180559945309417 answer = 0 for i in range (1,40): answer += -(-1)**i * ((mantissa - 1)**i/i) return(answer + exponent * ln2)
def PyNextAfter(x, y): """returns the next float after x in the direction of y if possible, else returns x""" # if x or y is Nan, we don't do much if IsNaN(x) or IsNaN(y): return x # we can't progress if x == y if x == y: return x # similarly if x is infinity if x >= infinity or x <= -infinity: return x # return small numbers for x very close to 0.0 if -minFloat < x < minFloat: if y > x: return x + smallEpsilon else: return x - smallEpsilon # we know x != y # it looks like we have a normalized number # break x down into a mantissa and exponent m, e = math.frexp(x) # all the special cases have been handled if y > x: m += epsilon else: m -= epsilon return math.ldexp(m, e)
def _write_float(f, x): import math if x < 0: sign = 0x8000 x = x * -1 else: sign = 0 if x == 0: expon = 0 himant = 0 lomant = 0 else: fmant, expon = math.frexp(x) if expon > 16384 or fmant >= 1: # Infinity or NaN expon = sign|0x7FFF himant = 0 lomant = 0 else: # Finite expon = expon + 16382 if expon < 0: # denormalized fmant = math.ldexp(fmant, expon) expon = 0 expon = expon | sign fmant = math.ldexp(fmant, 32) fsmant = math.floor(fmant) himant = long(fsmant) fmant = math.ldexp(fmant - fsmant, 32) fsmant = math.floor(fmant) lomant = long(fsmant) _write_short(f, expon) _write_long(f, himant) _write_long(f, lomant)
def descr_hex(self, space): TOHEX_NBITS = rfloat.DBL_MANT_DIG + 3 - (rfloat.DBL_MANT_DIG + 2) % 4 value = self.floatval if not isfinite(value): return self.descr_str(space) if value == 0.0: if copysign(1., value) == -1.: return space.wrap("-0x0.0p+0") else: return space.wrap("0x0.0p+0") mant, exp = math.frexp(value) shift = 1 - max(rfloat.DBL_MIN_EXP - exp, 0) mant = math.ldexp(mant, shift) mant = abs(mant) exp -= shift result = ['\0'] * ((TOHEX_NBITS - 1) // 4 + 2) result[0] = _char_from_hex(int(mant)) mant -= int(mant) result[1] = "." for i in range((TOHEX_NBITS - 1) // 4): mant *= 16.0 result[i + 2] = _char_from_hex(int(mant)) mant -= int(mant) if exp < 0: sign = "-" else: sign = "+" exp = abs(exp) s = ''.join(result) if value < 0.0: return space.wrap("-0x%sp%s%d" % (s, sign, exp)) else: return space.wrap("0x%sp%s%d" % (s, sign, exp))
def as_integer_ratio(self, a, **args): """Convert real number to a (numer, denom) pair. """ v, n = math.frexp(a) # XXX: hack, will work only for floats for i in xrange(300): if v != math.floor(v): v, n = 2*v, n - 1 else: break numer, denom = int(v), 1 m = 1 << abs(n) if n > 0: numer *= m else: denom = m n, d = self.limit_denom(numer, denom, **args) if a and not n: return numer, denom else: return n, d
def set_ref(self, refval): x = self.teach() m,e = math.frexp(refval / 5e-9) if m < 0: s = 0x80 m = -m else: s = 0 m = math.ldexp(m, -1) for i in range(14,20): m = math.ldexp(m, 8) h = int(m) m -= h x[i] = s | h s = 0 e -= 31 if e < 0: e += 256 x[20] = e y=bytearray("LN") for i in x: if i == 10 or i == 27 or i == 13 or i == 43: y.append(27) y.append(i) d.wr(y)
def _bus_message_received_cb(self, bus, message): """ @param bus: the message bus sending the message @param message: the message received """ if message.get_structure().get_name() == 'level': s = message.get_structure() peak = list(s['peak']) decay = list(s['decay']) rms = list(s['rms']) for l in peak, decay, rms: for index, v in enumerate(l): try: v = frexp(v) except (SystemError, OverflowError, ValueError): # It was an invalid value (e.g. -Inf), so clamp to # something appropriate l[index] = -100.0 if not self.uiState: self.warning("effect %s doesn't have a uiState" % self.name) else: for k, v in ('peak', peak), ('decay', decay), ('rms', rms): self.uiState.set('volume-%s' % k, v) if not self.firstVolumeValueReceived: self.uiState.set('volume-volume', self.effect_getVolume()) self.firstVolumeValueReceived = True
def msum(iterable): """Full precision summation. Compute sum(iterable) without any intermediate accumulation of error. Based on the 'lsum' function at http://code.activestate.com/recipes/393090/ """ tmant, texp = 0, 0 for x in iterable: mant, exp = math.frexp(x) mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig if texp > exp: tmant <<= texp-exp texp = exp else: mant <<= exp-texp tmant += mant # Round tmant * 2**texp to a float. The original recipe # used float(str(tmant)) * 2.0**texp for this, but that's # a little unsafe because str -> float conversion can't be # relied upon to do correct rounding on all platforms. tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp) if tail > 0: h = 1 << (tail-1) tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1) texp += tail return math.ldexp(tmant, texp)
def _write_float(f, x): import math if x < 0: sign = 32768 x = x * -1 else: sign = 0 if x == 0: expon = 0 himant = 0 lomant = 0 else: fmant, expon = math.frexp(x) if expon > 16384 or fmant >= 1 or fmant != fmant: expon = sign | 32767 himant = 0 lomant = 0 else: expon = expon + 16382 if expon < 0: fmant = math.ldexp(fmant, expon) expon = 0 expon = expon | sign fmant = math.ldexp(fmant, 32) fsmant = math.floor(fmant) himant = long(fsmant) fmant = math.ldexp(fmant - fsmant, 32) fsmant = math.floor(fmant) lomant = long(fsmant) _write_ushort(f, expon) _write_ulong(f, himant) _write_ulong(f, lomant)
def get01(self, x): m, e = math.frexp(self._base - x) if m >= 0 and e <= _E_MAX: v = (e + m) / (2. * _E_MAX) return 1 - v else: return 1 if m < 0 else 0
def get01(self, x): m, e = math.frexp(x - self._base) if m >= 0 and e <= _E_MAX: v = (e + m) / (2. * _E_MAX) return v else: return 0 if m < 0 else 1
print(math.factorial(6)) print(math.factorial(12)) # Round a number downward to its nearest integer print(math.floor(1.4)) print(math.floor(5.3)) print(math.floor(-5.3)) print(math.floor(22.6)) # Return the remainder after modulo operation print(math.fmod(67, 7)) print(math.fmod(17, 4)) print(math.fmod(16, 4)) #Return mantissa and exponent of a given number print(math.frexp(4)) print(math.frexp(7.9)) # Print the sum of all items print(math.fsum((1, 2, 3, 4, 5))) #find the highest number that can divide two numbers print(math.gcd(26, 12)) print(math.gcd(12, 6)) print(math.gcd(10, 0)) print(math.gcd(0, 34)) print(math.gcd(0, 0)) #compare the closeness of two values print(math.isclose(1.233, 1.4566)) print(math.isclose(1.233, 1.233))
def t_math(n1): nf = math.ceil(n1) ng = math.floor(n1) nh = math.frexp(n1) print 'ceil:%s,floor:%s,frexp:%s' % (nf, ng, nh)
def __floor__(self): return 'floor' assert math.trunc(A()) == 'trunc' assert math.ceil(A()) == 'ceil' assert math.floor(A()) == 'floor' with assertRaises(TypeError): math.trunc(object()) with assertRaises(TypeError): math.ceil(object()) with assertRaises(TypeError): math.floor(object()) assert str(math.frexp(0.0)) == str((+0.0, 0)) assert str(math.frexp(-0.0)) == str((-0.0, 0)) assert math.frexp(1) == (0.5, 1) assert math.frexp(1.5) == (0.75, 1) assert math.frexp(float('inf')) == (float('inf'), 0) assert str(math.frexp(float('nan'))) == str((float('nan'), 0)) assert_raises(TypeError, lambda: math.frexp(None)) assert math.gcd(0, 0) == 0 assert math.gcd(1, 0) == 1 assert math.gcd(0, 1) == 1 assert math.gcd(1, 1) == 1 assert math.gcd(-1, 1) == 1 assert math.gcd(1, -1) == 1 assert math.gcd(-1, -1) == 1
def floor_log(x): return math.frexp(x)[1] - 1
def quantize_scale(scale): significand, shift = math.frexp(scale) significand_q31 = round(significand * (1 << 31)) return significand_q31, shift
def frexp(x): return math.frexp(x)
def neon_math_frexp(self): x = self.stack.pop().value (m, e) = math.frexp(float(x)) self.stack.append(Value(decimal.Decimal(e))) self.stack.append(Value(decimal.Decimal(m)))
import math print(dir(math)) print(math.ceil(-1)) print(math.ceil(1.024)) print(math.copysign(1, -1)) print(math.fabs(-1)) print(math.factorial(5)) print(math.floor(-1.024)) print(math.floor(1.024)) print(math.fmod(1, 2)) print(math.frexp(1024)) print(math.fsum([1, 2, 3, 4, 5, 6, 7, 8])) print(math.gcd(3, 9)) print(math.exp(3)) print(math.expm1(3)) print(math.log(10, 24)) print(math.log1p(1024)) print(math.log2(1024)) print(math.log(10)) print(math.log10(100)) print(math.pow(3, 3)) print(math.sqrt(81)) print('------------------------')
def fn(x): res = frexp(x) return res[0] + float(res[1])
assertEqual(math.fmod(-3.0, INF), -3.0) assertEqual(math.fmod(3.0, NINF), 3.0) assertEqual(math.fmod(-3.0, NINF), -3.0) assertEqual(math.fmod(0.0, 3.0), 0.0) assertEqual(math.fmod(0.0, NINF), 0.0) doc="Frexp" assertRaises(TypeError, math.frexp) def testfrexp(name, result, expected): (mant, exp), (emant, eexp) = result, expected if abs(mant-emant) > eps or exp != eexp: fail('%s returned %r, expected %r'%\ (name, result, expected)) testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1)) testfrexp('frexp(0)', math.frexp(0), (0, 0)) testfrexp('frexp(1)', math.frexp(1), (0.5, 1)) testfrexp('frexp(2)', math.frexp(2), (0.5, 2)) assertEqual(math.frexp(INF)[0], INF) assertEqual(math.frexp(NINF)[0], NINF) assertTrue(math.isnan(math.frexp(NAN)[0])) doc="Fsum" # math.fsum relies on exact rounding for correct operation. # There's a known problem with IA32 floating-point that causes # inexact rounding in some situations, and will cause the # math.fsum tests below to fail; see issue #2937. On non IEEE # 754 platforms, and on IEEE 754 platforms that exhibit the # problem described in issue #2937, we simply skip the whole
def frexp(self): import math return AdvTuple(math.frexp(self))
def test_frexp(self): self.assertRaises(TypeError, math.frexp) def testfrexp(name, result, expected): (mant, exp), (emant, eexp) = result, expected if abs(mant - emant) > eps or exp != eexp: self.fail('%s returned %r, expected %r'%\ (name, result, expected)) testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1)) testfrexp('frexp(0)', math.frexp(0), (0, 0)) testfrexp('frexp(1)', math.frexp(1), (0.5, 1)) testfrexp('frexp(2)', math.frexp(2), (0.5, 2)) self.assertEqual(math.frexp(INF)[0], INF) self.assertEqual(math.frexp(NINF)[0], NINF) self.assertTrue(math.isnan(math.frexp(NAN)[0])) testfrexp('frexp(True)', math.frexp(True), (0.5, 1)) testfrexp('frexp(False)', math.frexp(False), (0.0, 0)) testfrexp('frexp(6227020800)', math.frexp(6227020800), (0.7249206304550171, 33)) testfrexp('frexp(2432902008176640000999)', math.frexp(2432902008176640000999), (0.5151870395916913, 72)) self.assertRaises(TypeError, math.frexp, 'hello') class X(int): def getX(): return 'Ahoj' class Y(float): def getY(): return 'Ahoj' testfrexp('frexp(X(10))', math.frexp(X(10)), (0.625, 4)) testfrexp('frexp(Y(11.11))', math.frexp(Y(11.11)), (0.694375, 4))
print 'fmod' testit('fmod(10,1)', math.fmod(10,1), 0) testit('fmod(10,0.5)', math.fmod(10,0.5), 0) testit('fmod(10,1.5)', math.fmod(10,1.5), 1) testit('fmod(-10,1)', math.fmod(-10,1), 0) testit('fmod(-10,0.5)', math.fmod(-10,0.5), 0) testit('fmod(-10,1.5)', math.fmod(-10,1.5), -1) print 'frexp' def testfrexp(name, (mant, exp), (emant, eexp)): if abs(mant-emant) > eps or exp != eexp: raise TestFailed, '%s returned %s, expected %s'%\ (name, `mant, exp`, `emant,eexp`) testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1)) testfrexp('frexp(0)', math.frexp(0), (0, 0)) testfrexp('frexp(1)', math.frexp(1), (0.5, 1)) testfrexp('frexp(2)', math.frexp(2), (0.5, 2)) print 'hypot' testit('hypot(0,0)', math.hypot(0,0), 0) testit('hypot(3,4)', math.hypot(3,4), 5) print 'ldexp' testit('ldexp(0,1)', math.ldexp(0,1), 0) testit('ldexp(1,1)', math.ldexp(1,1), 2) testit('ldexp(1,-1)', math.ldexp(1,-1), 0.5) testit('ldexp(-1,1)', math.ldexp(-1,1), -2) print 'log'
# constant to be used when iterating with range() over all considered quantum effects # (range() is exclusive with respect to the last element) S_LAST_INDEX = 1 # construction of aCLIMAX constant which is used to evaluate mean square displacement (u) with warnings.catch_warnings(record=True) as warning_list: warnings.simplefilter("always") H_BAR = constants.codata.value( "Planck constant over 2 pi" ) # H_BAR = 1.0545718e-34 [J s] = [kg m^2 / s ] if len(warning_list) >= 1 and isinstance(warning_list[0].message, ConstantWarning): H_BAR = constants.hbar # H_BAR = 1.0545718e-34 [J s] = [kg m^2 / s ] H_BAR_DECOMPOSITION = math.frexp(H_BAR) M2_TO_ANGSTROM2 = 1.0 / constants.angstrom**2 # m^2 = 10^20 A^2 M2_TO_ANGSTROM2_DECOMPOSITION = math.frexp(M2_TO_ANGSTROM2) KG2AMU = constants.codata.value( "kilogram-atomic mass unit relationship") # kg = 6.022140857e+26 amu KG2AMU_DECOMPOSITION = math.frexp(KG2AMU) # here we divide by 100 because we need relation between hertz and inverse cm HZ2INV_CM = constants.codata.value( "hertz-inverse meter relationship" ) / 100 # Hz [s^1] = 3.33564095198152e-11 [cm^-1] HZ2INV_CM_DECOMPOSITION = math.frexp(HZ2INV_CM) # Conversion factor from VASP internal units
import math pow(3, 2) for i in range(1, 11): print(pow(i, 2)) # for print the square of first 10 numbers print(pow(i, 3)) # for print the cube of first 10 numbers print(pow(i, 0.5)) # for print the square root of first 10 numbers lst = [11, 32, 34, 54, 67, 87, 24, 55, 36, 87] max(lst) # returns the maximum numbers min(lst) # returns the minimum numbers math.ceil(5) # ceil and floor numbers math.copysign(5, -1) # copy the sign of y math.factorial(5) # returns the factorial of the numbers math.fmod(40, 6) # returns the remainder math.frexp(5) # returns the exponent of x as the pair of (m,e) math.sum(lst) # returns the sum of the values present math.exp(5) # returns the exponent of (e,5) math.expm1(6) # returns the value of e**x-1 math.sqrt(5) # returns the square root of x math.gcd(46, 84) # returns the greatest common divisor math.lcm(25, 20) # returns the least common multiple math.nextafter( 34, 36 ) # returns the next number in floting point either towards zero/opposite math.prod(lst) # returns the product of all availale iterables math.remainder(6, 5) # returns the reaminder
assert d == {'a': 1, 'b': 2.1} assert type(d['a']) == int assert type(d['b']) == float # issue 203 def f(z): z += 1 return z x = 1.0 assert x != f(x) # issue 204 import math m, e = math.frexp(abs(123.456)) assert m == 0.9645 assert m * (1 << 24) == 16181624.832 # issue 207 for x in range(0x7ffffff0, 0x8000000f): assert x & x == x, "%s & %s == %s" % (hex(x), hex(x), hex(x & x)) assert x | x == x, "%s | %s == %s" % (hex(x), hex(x), hex(x | x)) for x in range(0x17ffffff0, 0x17fffffff): assert x & x == x, "%s & %s == %s" % (hex(x), hex(x), hex(x & x)) assert x | x == x, "%s | %s == %s" % (hex(x), hex(x), hex(x | x)) # issue 208 a=5
def test_frexp(self, space): w_res = space.execute("return Math.frexp(1234)") assert self.unwrap(space, w_res) == [math.frexp(1234)[0], 11]
def round_double(value, ndigits, half_even=False): """Round a float half away from zero. Specify half_even=True to round half even instead. The argument 'value' must be a finite number. This function may return an infinite number in case of overflow (only if ndigits is a very negative integer). """ if ndigits == 0: # fast path for this common case if half_even: return round_half_even(value) else: return round_away(value) if value == 0.0: return 0.0 # The basic idea is very simple: convert and round the double to # a decimal string using _Py_dg_dtoa, then convert that decimal # string back to a double with _Py_dg_strtod. There's one minor # difficulty: Python 2.x expects round to do # round-half-away-from-zero, while _Py_dg_dtoa does # round-half-to-even. So we need some way to detect and correct # the halfway cases. # a halfway value has the form k * 0.5 * 10**-ndigits for some # odd integer k. Or in other words, a rational number x is # exactly halfway between two multiples of 10**-ndigits if its # 2-valuation is exactly -ndigits-1 and its 5-valuation is at # least -ndigits. For ndigits >= 0 the latter condition is # automatically satisfied for a binary float x, since any such # float has nonnegative 5-valuation. For 0 > ndigits >= -22, x # needs to be an integral multiple of 5**-ndigits; we can check # this using fmod. For -22 > ndigits, there are no halfway # cases: 5**23 takes 54 bits to represent exactly, so any odd # multiple of 0.5 * 10**n for n >= 23 takes at least 54 bits of # precision to represent exactly. sign = copysign(1.0, value) value = abs(value) # find 2-valuation value m, expo = math.frexp(value) while m != math.floor(m): m *= 2.0 expo -= 1 # determine whether this is a halfway case. halfway_case = 0 if not half_even and expo == -ndigits - 1: if ndigits >= 0: halfway_case = 1 elif ndigits >= -22: # 22 is the largest k such that 5**k is exactly # representable as a double five_pow = 1.0 for i in range(-ndigits): five_pow *= 5.0 if math.fmod(value, five_pow) == 0.0: halfway_case = 1 # round to a decimal string; use an extra place for halfway case strvalue = formatd(value, 'f', ndigits + halfway_case) if not half_even and halfway_case: buf = [c for c in strvalue] if ndigits >= 0: endpos = len(buf) - 1 else: endpos = len(buf) + ndigits # Sanity checks: there should be exactly ndigits+1 places # following the decimal point, and the last digit in the # buffer should be a '5' if not objectmodel.we_are_translated(): assert buf[endpos] == '5' if '.' in buf: assert endpos == len(buf) - 1 assert buf.index('.') == len(buf) - ndigits - 2 # increment and shift right at the same time i = endpos - 1 carry = 1 while i >= 0: digit = ord(buf[i]) if digit == ord('.'): buf[i + 1] = chr(digit) i -= 1 digit = ord(buf[i]) carry += digit - ord('0') buf[i + 1] = chr(carry % 10 + ord('0')) carry /= 10 i -= 1 buf[0] = chr(carry + ord('0')) if ndigits < 0: buf.append('0') strvalue = ''.join(buf) return sign * rstring_to_float(strvalue)
def compare_floats(v, val): from math import frexp vm, ve = frexp(val) scale = 2.0**(-ve) delta = abs(v * scale - val * scale) return delta < 1.e-14
import math # Sign Manipulation print(math.copysign( -2, -1)) # Copy the sign of the second arg to the first and return it. print(math.fabs(-2)) # Return the absolute value # Sequences print(math.factorial(5)) # Return the value of !5 # Working with Floats print(math.frexp(5)) print(math.ldexp(.625, 3)) print(sum([.1] * 10)) # Precision limited to 16 decimal points. print(math.fsum([.1] * 10)) # Accurately sum floats to infinite precision # Modulus print(math.fmod(-1e-100, 1e100)) # Accurate modulus for working with floats print(math.modf(5.123456)) print(math.remainder(37.123, 7)) print(37.123 % 7) # Factoring print(math.gcd(35, 3500), math.gcd(42, 2996)) # Testing for numeric attributes print(math.isfinite(math.inf)) print(math.isfinite(0.0)) print(math.isinf(math.inf)) print(math.isnan(float('nan'))) print(
def quantize_scale(scale): multiplier, shift = math.frexp(scale) multiplier_q31 = round(multiplier * (1 << 31)) return multiplier_q31, shift
TEST_VALUES.append( rand ) for t in sorted(TEST_VALUES): print fmt.format(t, int(t), math.trunc(t), math.floor(t), math.ceil(t) ) print ## 5.4.4 Alternate Representations # modf separates the number into a (portion, whole) for i in xrange(6): print '{}/2 = {}'.format(i, math.modf(i/2.0)) print # frexp(x) returns (m, e), where x = m + 2**e print ' '.join(['{:^7}'] * 3).format('x','m','e') print ' '.join(['{:-^7}'] * 3).format('','','') for x in [0.1, 0.5, 4.0]: m,e = math.frexp(x) print '{:7.2f} {:7.2f} {:7d}'.format( x, m, e ) # ldexp(m,e) returns x, where x = m + 2**e print ' '.join(['{:^7}'] * 3).format('m','e','x') print ' '.join(['{:-^7}'] * 3).format('','','') for m,e in [ (0.8, -3), (0.5, 0), (0.5, 3) ]: x = math.ldexp(m, e) print '{:7.2f} {:7d} {:7.2f}'.format( m, e, x ) print ## 5.4.5 Positive and Negative Signs print math.fabs(-1.1) print math.fabs(-0.0) print math.fabs( 0.0) print math.fabs( 1.1)
def frexp(x): if isinstance(x, LineValue): lx = x.get_value() else: lx = x if lx == NAN: return LineValue(NAN) return LineValue(math.frexp(lx))
def solve_control(density, velocity, target, remaining_time, level_control=False, velocity_generator=multi_scale_control_cnn_16_2): rank = spatial_rank(density) size = int(max(density.shape[1:])) # Create density grids density_grids = [to_dipole_format(density)] target_grids = [to_dipole_format(target)] velocity_grids = [velocity] for i in range(pymath.frexp(float(size))[1] - 1): # downsample until 1x1 density_grids.insert(0, moment_downsample2x(density_grids[0], sum=True)) target_grids.insert(0, moment_downsample2x(target_grids[0], sum=True)) velocity_grids.insert(0, downsample2x(velocity_grids[0])) added_velocity = None level_scalings = [] velocities_by_level = [] for i in range(len(density_grids)): density_grid = density_grids[i] target_grid = target_grids[i] velocity_grid = velocity_grids[i] if added_velocity is None: combined_velocity = velocity_grid else: added_velocity = upsample2x(added_velocity)[:, 2:-2, 2:-2, :] combined_velocity = velocity_grid + added_velocity # Add border pixel for smooth upsampling at the edges padded_density = tf.pad(density_grid, [[0, 0]] + [[1, 1]] * rank + [[0, 0]]) padded_target = tf.pad(target_grid, [[0, 0]] + [[1, 1]] * rank + [[0, 0]]) padded_velocity = tf.pad(combined_velocity, [[0, 0]] + [[1, 1]] * rank + [[0, 0]]) if added_velocity is not None: added_velocity = tf.pad(added_velocity, [[0, 0]] + [[1, 1]] * rank + [[0, 0]], mode="SYMMETRIC") added_velocity_lvl = velocity_generator(padded_density, padded_velocity, padded_target, remaining_time, i) velocities_by_level.append(added_velocity_lvl) level_scaling = create_level_scaling(level_control, i) level_scalings.append(level_scaling) if added_velocity is None: added_velocity = added_velocity_lvl * level_scaling else: added_velocity += added_velocity_lvl * level_scaling return added_velocity[:, 1:-1, 1:-1, :], (level_scalings, velocities_by_level)
#Урок номер 6 по модулю Math import math print("Длина строки", len("123")) print("Округление", round(8.6)) print("Число ПИ", math.pi) print("Число эллера", math.e) print("Возведение в степень", math.pow(2, 3)) # 2**3 print("Остаток от деления", math.fmod(7, 3)) # 7%3 x = 5 print("Проверка на число", math.isfinite(x)) print("Проверка на бесконечность", math.isinf(x)) print("Мантисса и экспонента", math.frexp(123.456)) print("Квадратный корень", math.sqrt(9)) print("Модуль", math.fabs(-20)) print("Модуль числа 1, со знаком числа 2", math.copysign(-10, 5)) print("Отделяет целую часть и дробную", math.modf(123.456)) print("Округление в большую", math.ceil(4.1)) print("Округление в меньшую", math.floor(4.9)) print("Отбрасывание дробной части", math.trunc(8.9)) print("Отбрасывание дробной части", math.trunc(8.9)) print("Косинус угла", math.cos(math.radians(60))) print("Синус угла", math.sin(math.radians(30))) print("Тангенс угла", math.tan(math.radians(45))) print("Гипотенуза", math.hypot(3, 4)) print("Логaрифм", math.log(8, 2)) print("Логaрифм десятичный", math.log10(100)) input()
def entry_point(argv): m, e = math.frexp(0) x, y = math.frexp(0) print m, x return 0
class FixedPoint: # the exact value is self.n / 10**self.p; # self.n is a long; self.p is an int def __init__(self, value=0, precision=DEFAULT_PRECISION): self.n = self.p = 0 self.set_precision(precision) p = self.p if isinstance(value, type("42.3e5")): n, exp = _string2exact(value) # exact value is n*10**exp = n*10**(exp+p)/10**p effective_exp = exp + p if effective_exp > 0: n = n * _tento(effective_exp) elif effective_exp < 0: n = _roundquotient(n, _tento(-effective_exp)) self.n = n return if isinstance(value, type(42)) or isinstance(value, type(42L)): self.n = long(value) * _tento(p) return if isinstance(value, FixedPoint): temp = value.copy() temp.set_precision(p) self.n, self.p = temp.n, temp.p return if isinstance(value, type(42.0)): # XXX ignoring infinities and NaNs and overflows for now import math f, e = math.frexp(abs(value)) assert f == 0 or 0.5 <= f < 1.0 # |value| = f * 2**e exactly # Suck up CHUNK bits at a time; 28 is enough so that we suck # up all bits in 2 iterations for all known binary double- # precision formats, and small enough to fit in an int. CHUNK = 28 top = 0L # invariant: |value| = (top + f) * 2**e exactly while f: f = math.ldexp(f, CHUNK) digit = int(f) assert digit >> CHUNK == 0 top = (top << CHUNK) | digit f = f - digit assert 0.0 <= f < 1.0 e = e - CHUNK # now |value| = top * 2**e exactly # want n such that n / 10**p = top * 2**e, or # n = top * 10**p * 2**e top = top * _tento(p) if e >= 0: n = top << e else: n = _roundquotient(top, 1L << -e) if value < 0: n = -n self.n = n return if isinstance(value, type(42 - 42j)): raise TypeError("can't convert complex to FixedPoint: " + ` value `) # can we coerce to a float? yes = 1 try: asfloat = float(value) except: yes = 0 if yes: self.__init__(asfloat, p) return # similarly for long yes = 1 try: aslong = long(value) except: yes = 0 if yes: self.__init__(aslong, p) return raise TypeError("can't convert to FixedPoint: " + ` value `)
# 25 # Return True if the values a and b are close to each other and False otherwise. math.isclose(1.000000002, 1.000000001) # True math.isclose(1.000000003, 1.000000001) # False # base-2 logarithm of x x = 2 # -> float math.log(x, 2.0) # slow math.log2(x) # 1.0 # -> int math.frexp(x)[1] - 1 # fast x.bit_length() - 1 # faster # 1 # decimal: accurate decimal math, eg: for money from decimal import Decimal sum(0.1 for i in range(1000)) # 99.9999999999986 sum(Decimal('0.1') for i in range(1000)) # Decimal('100.0') Decimal(0.1) # be careful converting from floats! # Decimal('0.1000000000000000055511151231257827021181583404541015625') def digits(n: int) -> Generator[int, None, None]: # How to get the digits of an integer
def compare_floats(v, val): vm, ve = math.frexp(val) scale = 2.0**(-ve) delta = abs(v*scale - val*scale) return delta < 1.e-14
def method_frexp(self, space, value): mant, exp = math.frexp(value) w_mant = space.newfloat(mant) w_exp = space.newint(exp) return space.newarray([w_mant, w_exp])