def applyPower(self, conf_list, power): mtop = clnum.mpf(max(conf_list)[0]) s = clnum.mpf(0.0) for t in conf_list: t[0] = pow(power, pow(power, mtop - clnum.mpf(t[0]))) s += t[0] for t in conf_list: t[0] = t[0]/s return conf_list
def number_str(s, prec=0, prefer_cmpf=False): '''Given a string, try to convert it to one of the supported number types. The following are applied in order: int, long, mpq, mpf, cmpq, cmpf unless prefer_cmpf is True. Then cmpq and cmpf are swapped. Integers (int,long) can have an optional base prefix: 0x - hex 0o - octal 0b - binary The floating point forms (mpf,cmpf) accept an optional prec parameter which defaults to the current clnum module default. ''' s = _clean_str(s) # Save and remove the sign since it interferes with the base recognition. sign = 1 si = s if s.startswith('-'): sign = -1 si = s[1:] elif s.startswith('+'): si = s[1:] # Identify the base to use for the conversion. bases = {'0X':16, '0O':8, '0B':2} prefix = si[:2] base = 10 if prefix in bases: si = si[2:] base = bases[prefix] try: return sign*int(si, base) except ValueError: pass try: return sign*long(si, base) except ValueError: pass if base != 10: raise ValueError('Cannot apply base prefix to non-integers') # Import the clnum module here to avoid circular import when clnum is # initializing. import clnum # NOTE: The original string is used from here on because the modified form # would cause errors in complex numbers. try: return clnum.mpq(s) except ValueError: pass try: return clnum.mpf(s, prec=prec) except ValueError: pass if prefer_cmpf: try: return clnum.cmpf(s, prec=prec) except ValueError: pass try: return clnum.cmpq(s) except ValueError: pass else: try: return clnum.cmpq(s) except ValueError: pass try: return clnum.cmpf(s, prec=prec) except ValueError: pass raise ValueError('Cannot convert string to a number')