def to_xml_element(self): """Creats a result XML element.""" # Creating result element : This is a root for each result but a subelement for the results file result_elem = ET.Element("result") precision = self.__calculation_conditions.get_precision() # Creating conditions element conditions_elem = ET.SubElement(result_elem, "conditions") # Creating pi element pi_elem = ET.SubElement(conditions_elem, "pi") pi_algorithm = ET.SubElement(pi_elem, "algorithm").text = self.__calculation_conditions.get_pi_algorithm().name pi_val_elem = ET.SubElement(pi_elem, "value").text = nstr(self.__pi, precision) # Creating Alpha Element alpha_elem = ET.SubElement(conditions_elem, "alpha") alpha_algorithm = ET.SubElement(alpha_elem, "algorithm").text = self.__calculation_conditions.get_approximation_algorithm().name alpha_precision = ET.SubElement(alpha_elem, "precision").text = str(precision) alpha_value = ET.SubElement(alpha_elem, "value").text = nstr(self.__alpha, precision) # Creating radius and length radius_elem = ET.SubElement(result_elem, "radius").text = nstr(self.__coaster_radius, precision) overlap_len_elem = ET.SubElement(result_elem, "overlaplength").text = nstr(self.__overlapping_length, precision) return result_elem
def __str__(self): """Converts the object to a string suitable to be presented to the user.""" precision = self.__calculation_conditions.get_precision() result_str = "Pi calculation algorithm: {}\nPi is: {}\n" result_str += "Approximation algorithm for alpha: {}\n" result_str += "Alpha angle must be: {}\nCoasters radius: {}\n" result_str += "Length of the overlapping segment: {}" result_str = result_str.format(self.__calculation_conditions.get_pi_algorithm().name, self.__pi, self.__calculation_conditions.get_approximation_algorithm().name, self.__alpha, nstr(self.__coaster_radius, precision), nstr(self.__overlapping_length, precision)) # result_str = "Based on the specified conditions,\nPi number calculated using {}" # result_str += "" + self.__calculation_conditions.get_pi_algorithm().name # result_str += " algorithm as {}" + self.__pi + "\n" # result_str += "Alpha angle calculated using {}" + self.__calculation_conditions.get_approximation_algorithm().name # result_str += " algorithm as {}" + self.__alpha + "\n" # result_str += "Given the value of coasters radius as {}" + nstr(self.__coaster_radius, precision) + ", " # result_str += "length of the overlapping section must be {}" + nstr(self.__overlapping_length, precision) return result_str
def save_cheb(dir_name: str, n: int) -> None: pts = cheb_pts(n) cheb_D_matrix = cheb_D(n) to_cheb, to_real = compute_to_cheb_to_real(n) with open(dir_name + "/cheb_to_real.txt", "w") as f: for line in to_real: for val in line: f.write(mp.nstr(val, 32) + ' ') f.write('\n') with open(dir_name + "/real_to_cheb.txt", "w") as f: for line in to_cheb: for val in line: f.write(mp.nstr(val, 32) + ' ') f.write('\n') with open(dir_name + "/cheb_pts.txt", "w") as f: for val in pts: f.write(mp.nstr(val, 32) + '\n') with open(dir_name + "/cheb_D.txt", "w") as f: for line in cheb_D_matrix: for val in line: f.write(mp.nstr(val, 32) + ' ') f.write('\n')
def add_gwb(self, gwb, dist, InjectionFile="None", verbose=-1): """ Add GW background on simulated TOAs using a GWB object from libstempo and the pulsar distance in kpc.""" if verbose==-1 : verbose = self.verbose if verbose!=0 : print "Add GWB ..." #### Making libstempo.tempopulsar save in parfile and timfile localverbose=0 if verbose>1 : localverbose=1 self.savepar("TmpIdeal", verbose=localverbose) self.savetim("TmpIdeal",IdealTOAs=True, verbose=localverbose) psr = libstempo.tempopulsar(parfile="TmpIdeal.par",timfile="TmpIdeal.tim",dofit=False) #### Creating GWB data GWBval = gwb.add_gwb(psr,dist) #### Adding data fOut = None if InjectionFile!="None": fOut = open(InjectionFile,'w') fOut.write("#TOAIdeal GWB TOARelBeforeInjection TOARelAfterInjection DiffTOAAft-Bef\n") for itoa in xrange(len(self.timTOAs)) : TOABefInj = self.timTOAs[itoa][0] self.timTOAs[itoa][0] += mp.mpf(np.float64(GWBval[itoa]),n=self.prec) if fOut!=None : fOut.write(mp.nstr(self.timTOAsIdeal[itoa][0],n=self.prec)+" "+repr(GWBval[itoa])+" "\ +mp.nstr(TOABefInj-self.timTOAsIdeal[0][0],n=self.prec)+" "\ +mp.nstr(self.timTOAs[itoa][0]-self.timTOAsIdeal[0][0],n=self.prec)+" "\ +mp.nstr(self.timTOAs[itoa][0]-TOABefInj,n=self.prec)+"\n") if fOut!=None : fOut.close()
def verify_results(self, results): """ Validate intermediate results to 100 digit precision If a numeric value appears multiple times, the first is kept as valid. The rest saved as recurring for later. """ verified_results = [] recurring_value_results = {} res_set = set() for res in results: var_gen = lambdify((), res[0], modules="mpmath") a_ = create_series_from_shift_reg(res[3], res[2], self.verify_depth) b_ = (res[1] * ((self.verify_depth // len(res[1])) + 1)) b_ = b_[:self.verify_depth] gcf = EfficientGCF(a_, b_) with mpmath.workdps(self.verify_dps): lhs_str = mpmath.nstr(var_gen(), 100) rhs_val = gcf.evaluate() rhs_str = mpmath.nstr(rhs_val, 100) if rhs_str != lhs_str: continue key = lhs_str if key not in res_set: res_set.add(key) verified_results.append(res) recurring_value_results[key] = [] else: recurring_value_results[key].append(res) continue return verified_results, recurring_value_results
def mpf_assert_allclose(res, std, atol=0, rtol=1e-17): try: len(res) except TypeError: res = list(res) n = len(std) if len(res) != n: raise AssertionError("Lengths of inputs not equal.") failures = [] for k in range(n): try: assert_(mp.fabs(res[k] - std[k]) <= atol + rtol*mp.fabs(std[k])) except AssertionError: failures.append(k) ndigits = int(abs(np.log10(rtol))) msg = [""] msg.append("Bad results ({} out of {}) for the following points:" .format(len(failures), n)) for k in failures: resrep = mp.nstr(res[k], ndigits, min_fixed=0, max_fixed=0) stdrep = mp.nstr(std[k], ndigits, min_fixed=0, max_fixed=0) if std[k] == 0: rdiff = "inf" else: rdiff = mp.fabs((res[k] - std[k])/std[k]) rdiff = mp.nstr(rdiff, 3) msg.append("{}: {} != {} (rdiff {})".format(k, resrep, stdrep, rdiff)) if failures: assert_(False, "\n".join(msg))
def __refine_results(self, intermediate_results: List[Match], print_results=True): """ validate intermediate results to 100 digit precision :param intermediate_results: list of results from first enumeration :param print_results: if true print status. :return: final results. """ results = [] counter = 0 n_iterations = len(intermediate_results) constant_vals = [const() for const in self.constants_generator] for r in intermediate_results: counter += 1 if (counter % 50) == 0 and print_results: print( 'passed {} permutations out of {}. found so far {} matches' .format(counter, n_iterations, len(results))) try: val = self.hash_table.evaluate(r.lhs_key, constant_vals) if mpmath.isinf(val) or mpmath.isnan(val): # safety continue except (ZeroDivisionError, KeyError) as e: continue # create a_n, b_n with huge length, calculate gcf, and verify result. an = self.create_an_series(r.rhs_an_poly, g_N_verify_terms) bn = self.create_bn_series(r.rhs_bn_poly, g_N_verify_terms) gcf = EfficientGCF(an, bn) val_str = mpmath.nstr(val, g_N_verify_compare_length) rhs_str = mpmath.nstr(gcf.evaluate(), g_N_verify_compare_length) if val_str == rhs_str: results.append(r) return results
def mp_assert_allclose(res, std, atol=0, rtol=1e-17): """ Compare lists of mpmath.mpf's or mpmath.mpc's directly so that it can be done to higher precision than double. """ failures = [] for k, (resval, stdval) in enumerate(zip_longest(res, std)): if resval is None or stdval is None: raise ValueError('Lengths of inputs res and std are not equal.') if mpmath.fabs(resval - stdval) > atol + rtol * mpmath.fabs(stdval): failures.append((k, resval, stdval)) nfail = len(failures) if nfail > 0: ndigits = int(abs(np.log10(rtol))) msg = [""] msg.append( "Bad results ({} out of {}) for the following points:".format( nfail, k + 1)) for k, resval, stdval in failures: resrep = mpmath.nstr(resval, ndigits, min_fixed=0, max_fixed=0) stdrep = mpmath.nstr(stdval, ndigits, min_fixed=0, max_fixed=0) if stdval == 0: rdiff = "inf" else: rdiff = mpmath.fabs((resval - stdval) / stdval) rdiff = mpmath.nstr(rdiff, 3) msg.append("{}: {} != {} (rdiff {})".format( k, resrep, stdrep, rdiff)) assert_(False, "\n".join(msg))
def savetim(self, basename, sysname='all', multifile=False, IdealTOAs=False, verbose=-1): "Save TOA in tim file. It is strictly the original tim, except the column 3 and 4 corresponding to the new toa and error." if verbose==-1 : verbose = self.verbose if verbose!=0 : print "Save TOAs in",basename+".tim ..." fOut = open(basename+".tim",'w') for line in self.timHead : for iw in xrange(len(line)): if iw!=0: fOut.write(" ") fOut.write(line[iw]) fOut.write("\n") if multifile : os.system("mkdir -p "+basename) for xsys in self.syslist : fOut.write("INCLUDE "+os.path.basename(basename)+"/"+xsys+".tim\n") self.savetim(basename+"/"+xsys, sysname=xsys, multifile=False, IdealTOAs=IdealTOAs) else : tTOAs = self.timTOAs if IdealTOAs : tTOAs = self.timTOAsIdeal for tl in tTOAs : if sysname=='all' or sysname==tl[2] : tl[3][2] = "%s" % (mp.nstr(tl[0],n=self.prec)) # update the word corresponding to the TOAs tl[3][3] = "%s" % (mp.nstr(tl[1],n=self.prec)) # update the word corresponding to the errors ## Write tim line as a series of words for iw in xrange(len(tl[3])): if iw!=0 : fOut.write(" ") fOut.write(tl[3][iw]) fOut.write("\n") fOut.close()
def print_results(self, results, latex=True): """ Print results in either unicode or LaTex. :param results: verified results. :param latex: LaTex printing flag. """ for res_num, res in enumerate(results): var_sym = res[0] lfsr = res[3] cycle = res[1] initials = res[2] var_gen = lambdify((), var_sym, modules="mpmath") a_ = create_series_from_shift_reg(lfsr, initials, self.depth) b_ = (cycle * (self.depth // len(cycle)))[:self.depth] gcf = GeneralizedContinuedFraction(a_, b_) rate = calculate_convergence(gcf, lambdify((), var_sym, 'mpmath')()) if not latex: print(str(res_num)) print('lhs: ') sympy.pprint(var_sym) print('rhs :') gcf.print(8) print('lhs value: ' + mpmath.nstr(var_gen(), 50)) print('rhs value: ' + mpmath.nstr(gcf.evaluate(), 50)) print('a_n LFSR: {},\n With initialization: {}'.format(lfsr, initials)) print('b_n period: ' + str(cycle)) print("Converged with a rate of {} digits per term".format(mpmath.nstr(rate, 5))) else: equation = sympy.Eq(var_sym, gcf.sym_expression(5)) print('\n\n' + str(res_num + 1) + '. $$ ' + sympy.latex(equation) + ' $$\n') print('$\\{a_n\\}$ LFSR: \\quad \\quad \\quad \\quad \\;' + str(lfsr)) print('\n$\\{a_n\\}$ initialization: \\quad \\; ' + str(initials)) print('\n$\\{b_n\\}$ Sequence period: \\! ' + str(cycle)) print('\nConvergence rate: ${}$ digits per term\n\n'.format(mpmath.nstr(rate, 5)))
def calculateAllAverages(self, start, stop, receiver, emitter, avgMatrix): calculateNxxLookUp = mp.memoize(calculateNxx) calculateNxyLookUp = mp.memoize(calculateNxy) fLookUP = mp.memoize(f) gLookUP = mp.memoize(g) start = int(float(mp.nstr(start))) stop = int(float(mp.nstr(stop))) for j in range(start, stop): if (start == 0): val = (((j * 100) / receiver.nElements) * self.nThreads) print( mp.nstr(((j * 100) / receiver.nElements) * self.nThreads, 4), "%") self.emit(QtCore.SIGNAL('PROGRESS'), val) a11 = mp.mpf('0') a12 = mp.mpf('0') a13 = mp.mpf('0') a22 = mp.mpf('0') a23 = mp.mpf('0') a33 = mp.mpf('0') emEle = int(float(mp.nstr(emitter.nElements))) for i in range(emEle): delx, dely, delz = calculateDistance( emitter.smallBlocksStructure[i], receiver.smallBlocksStructure[j]) dx = emitter.widthSmall dy = emitter.depthSmall dz = emitter.heightSmall a11 += calculateNxxLookUp(delx, dely, delz, dx, dy, dz, emitter, fLookUP) a12 += calculateNxyLookUp(delx, dely, delz, dx, dy, dz, emitter, gLookUP) a13 += calculateNxyLookUp(delx, delz, dely, dx, dz, dy, emitter, gLookUP) a22 += calculateNxxLookUp(dely, delx, delz, dy, dx, dz, emitter, fLookUP) a23 += calculateNxyLookUp(dely, delz, delx, dy, dz, dx, emitter, gLookUP) # a31 = a13 # a32 = a23 a33 += calculateNxxLookUp(delz, dely, delx, dz, dy, dx, emitter, fLookUP) a11 = a11 / emitter.nElements a12 = a12 / emitter.nElements a13 = a13 / emitter.nElements a22 = a22 / emitter.nElements a23 = a23 / emitter.nElements a33 = a33 / emitter.nElements avgMatrix.append([a11, a12, a13, a12, a22, a23, a13, a23, a33]) return avgMatrix
def output(self, C): """Given the node <-> coordinates mapping, output the mapping on the screen. The coordinates are complex numbers.""" for n in sorted(C.keys()): cr = mpmath.nstr(C[n]['c'].real, 50) ci = mpmath.nstr(C[n]['c'].imag, 50) print "%s %s %s" % (n, cr, ci) pass
def generate(c, num_iterations=200): orbit_re = [] orbit_im = [] z = mpmath.mpc(real='0.0', imag='0.0') for _ in range(num_iterations): z = mpmath.fadd(mpmath.fmul(z, z), c) orbit_re.append(mpmath.nstr(mpmath.re(z))) orbit_im.append(mpmath.nstr(mpmath.im(z))) return [orbit_re, orbit_im]
def test_nstr(): m = matrix([[0.75, 0.190940654, -0.0299195971], [0.190940654, 0.65625, 0.205663228], [-0.0299195971, 0.205663228, 0.64453125e-20]]) assert nstr(m, 4, min_fixed=-inf) == \ '''[ 0.75 0.1909 -0.02992] [ 0.1909 0.6563 0.2057] [-0.02992 0.2057 0.000000000000000000006445]''' assert nstr(m, 4) == \ '''[ 0.75 0.1909 -0.02992]
def outprint(res): for k,v in res.items(): if isinstance(v, list): print("%-12s [%-23s %-23s %-23s %s]\t" % (k, mpmath.nstr(v[0], mpmath.mp.dps), mpmath.nstr(v[1], mpmath.mp.dps), mpmath.nstr(v[2], mpmath.mp.dps), mpmath.nstr(v[3], mpmath.mp.dps))) elif isinstance(v, BetaDistribution): print("%-12s [%-23s %-23s]\t" % (k, mpmath.nstr(v.mean(), mpmath.mp.dps), mpmath.nstr(v.variance(), mpmath.mp.dps))) else: raise Exception("Unclear data: %s" % (repr(v)))
def pariDilog(z): assert isinstance(z, mpmath.mpc) pariStr = 'myDilog = dilog((%s) + (%s) * I)' % ( mpmath.nstr(z.real, mpmath.mp.dps), mpmath.nstr(z.imag, mpmath.mp.dps)) pari_eval(pariStr) return mpmath.mpc( pari_eval('real(myDilog)').replace(' E','E'), pari_eval('imag(myDilog)').replace(' E','E'))
def main(): for p in range(1, 30): # get dbN coeffients dbN = daubechies(2 * p) # write coeffients filename = os.path.join( os.getcwd(), 'coefficients/daub' + str(2 * p).zfill(2) + '_coefficients.txt') print("Writing file {}".format(filename)) with open(filename, 'w+') as f: f.write('# Daubechies ' + str(2 * p) + ' scaling coefficients\n') f.write(" else if constexpr (N == " + str(2 * p) + ")\n {\n") f.write( " if constexpr (std::is_same<float, Real>::value) {\n return {" ) for i, h in enumerate(dbN): f.write(sm.nstr(h, 9) + 'f, ') f.write("};\n }\n") f.write( " else if constexpr (std::is_same<double, Real>::value) {\n return {" ) for i, h in enumerate(dbN): f.write(sm.nstr(h, 17) + ', ') f.write("};\n }\n") f.write( " else if constexpr (std::is_same<long double, Real>::value) {\n return {" ) for i, h in enumerate(dbN): # log2(64) + some leeway f.write(sm.nstr(h, 22) + 'L, ') f.write("};\n }\n") f.write(" #ifdef BOOST_HAS_FLOAT128\n") f.write( " else if constexpr (std::is_same<boost::multiprecision::float128, Real>::value) {\n return {" ) for i, h in enumerate(dbN): # log10(2**123) + some leeway f.write(sm.nstr(h, 37) + 'Q,\n ') f.write("};\n }\n") f.write(" #endif\n") f.write( ' else { throw std::logic_error("Wavelet transform coefficients for this precision have not been implemented."); }\n' ) f.write(" }\n") # get an approximation of scaling function '''x, phi, psi = scipy.signal.cascade(dbN)
def cacheResults( *args, **kwargs ): openFunctionCache( name ) lookup, result = lookUpFunctionCache( g.cursors[ name ], repr( args ) ) if lookup: return result result = func( *args, **kwargs ) print( ) print( nstr( result, n=mp.dps ), mp.dps ) print( ) saveToCache( g.databases[ name ], g.cursors[ name ], repr( args ), nstr( result, n=mp.dps ) ) return result
def main(): print(__doc__) print() stirling_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) for x in stirling_series(16)] taylor_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) for x in taylor_series_at_1(16)] print("Stirling series coefficients") print("----------------------------") print("\n".join(stirling_coeffs)) print() print("Taylor series coefficients") print("--------------------------") print("\n".join(taylor_coeffs)) print()
def _refine_results(self, intermediate_results: List[Match], print_results=True): """ validate intermediate results to 100 digit precision :param intermediate_results: list of results from first enumeration :param print_results: if true print status. :return: final results. """ results = [] counter = 0 n_iterations = len(intermediate_results) constant_vals = [const() for const in self.constants_generator] for res in intermediate_results: counter += 1 if (counter % 50) == 0 and print_results: print( 'passed {} permutations out of {}. found so far {} matches' .format(counter, n_iterations, len(results))) try: all_matches = self.hash_table.evaluate(res.lhs_key) # check if all values encountered are not inf or nan if not all([ not (mpmath.isinf(val) or mpmath.isnan(val)) for val, _, _ in all_matches ]): # safety print('Something wicked happened!') print( f'Encountered a NAN or inf in LHS db, at {res.lhs_key}, {constant_vals}' ) continue except (ZeroDivisionError, KeyError): # if there was an exeption here, there is no need to halt the entire execution, but only note it to the # user continue # create a_n, b_n with huge length, calculate gcf, and verify result. an = self.create_an_series(res.rhs_an_poly, g_N_verify_terms) bn = self.create_bn_series(res.rhs_bn_poly, g_N_verify_terms) gcf = EfficientGCF(an, bn) rhs_str = mpmath.nstr(gcf.evaluate(), g_N_verify_compare_length) for i, match in enumerate(all_matches): val_str = mpmath.nstr(match[0], g_N_verify_compare_length) if val_str == rhs_str: # This patch is ment to allow support for multiple matches for an # LHS key, i will later be used to determind which item in the LHS dict # was matched results.append(RefinedMatch(*res, i, match[1], match[2])) return results
def main(): print(__doc__) print() stirling_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) for x in stirling_series(8)[::-1]] taylor_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) for x in taylor_series_at_1(23)[::-1]] print("Stirling series coefficients") print("----------------------------") print("\n".join(stirling_coeffs)) print() print("Taylor series coefficients") print("--------------------------") print("\n".join(taylor_coeffs)) print()
def main(): sf_evals = UpdateSpecialFunctionsEvaluations( filename='test_spec_functions_data.hpp', complex_arguments=mia.complex_arguments, output_dps=30, max_num_elements_of_nlist=51) # output_dps=7, max_num_elements_of_nlist=51) # output_dps=5, max_num_elements_of_nlist=3) # sf_evals.run_test(mrb.D1, 'D1') # sf_evals.run_test(mrb.D2, 'D2') # sf_evals.run_test(mrb.D3, 'D3') # sf_evals.run_test(mrb.psi, 'psi', is_only_x=True) # sf_evals.run_test(mrb.xi, 'xi', is_only_x=True) # # In literature Zeta or Ksi denote the Riccati-Bessel function of third kind. # sf_evals.run_test(mrb.ksi, 'zeta', is_only_x=True) # sf_evals.run_test(mrb.an, 'an', is_xm=True) # sf_evals.run_test(mrb.bn, 'bn', is_xm=True) # sf_evals.run_test(mrb.psi, 'psi') # sf_evals.run_test(mrb.psi_div_ksi, 'psi_div_ksi') # sf_evals.run_test(mrb.psi_mul_ksi, 'psi_mul_zeta', is_only_x=True) # sf_evals.run_test(mrb.psi_div_xi, 'psi_div_xi') with open(sf_evals.filename, 'w') as out_file: out_file.write(sf_evals.get_file_content()) for record in mia.complex_arguments: mp.mp.dps = 20 output_dps = 16 x = mp.mpf(str(record[0])) mr = str(record[1][0]) mi = str(record[1][1]) m = mp.mpc(mr, mi) Qext_ref = record[2] Qsca_ref = record[3] test_case = record[4] nmax = int(x + 4.05 * x**(1. / 3.) + 2) + 2 + 28 print(f"\n ===== test case: {test_case} =====", flush=True) print( f"x={x}, m={m}, N={nmax} \nQsca_ref = {Qsca_ref} \tQext_ref = {Qext_ref}", flush=True) Qext_mp = mrb.Qext(x, m, nmax, output_dps) Qsca_mp = mrb.Qsca(x, m, nmax, output_dps) print( f"Qsca_mp = {mp.nstr(Qsca_mp[-1],output_dps)} \tQext_mp = {mp.nstr(Qext_mp[-1],output_dps)}", flush=True) print(mp.nstr(Qsca_mp, output_dps)) print(mp.nstr(Qext_mp, output_dps))
def print_results(self, results: List[Match], latex=False, convergence_rate=True): """ pretty print the the results. :param convergence_rate: if True calculate convergence rate and print it as well. :param results: list of final results as received from refine_results. :param latex: if True print in latex form, otherwise pretty print in unicode. """ formatted_results = self.__get_formatted_results(results) for r, raw_r in zip(formatted_results, results): result = sympy.Eq(r.LHS, r.RHS) if latex: print(f'$$ {sympy.latex(result)} $$') print( f'$$ {sympy.latex(self.__get_formatted_polynomials(raw_r))} $$\n' ) else: sympy.pprint(result) sympy.pprint(self.__get_formatted_polynomials(raw_r)) print('') if convergence_rate: with mpmath.workdps(self.verify_dps): rate = calculate_convergence( r.GCF, lambdify((), r.LHS, 'mpmath')()) print("Converged with a rate of {} digits per term".format( mpmath.nstr(rate, 5)))
def getMPFIntegerAsString( n ): '''Turns an mpmath mpf integer value into a string for use by lexicographic operators.''' if n == 0: return '0' else: return nstr( nint( n ), int( floor( log10( n ) + 10 ) ) )[ : -2 ]
def diagLevelL(L, N, m, magneticLength): """ Diagonalises the pertubation for angular momentum L above the Laughlin state with N particles and returns this as a list in the same format as the simular function in IQHEDiag module. """ states = genStates(L, N, m, magneticLength) numOfStates = len(states) halfMatrix = [[ waveFunctionClasses.waveFuncMatrixElement(states[i], states[j]) for j in range(i + 1) ] for i in range(numOfStates)] #halfMatrix = [[longFormMatrixElement(magneticLength, states[i], states[j]) for j in range(i+1)] for i in range(numOfStates)] transposedHalfMatrix = [[ halfMatrix[j][i] for j in range(i + 1, numOfStates) ] for i in range(numOfStates - 1)] print(transposedHalfMatrix) fullMatrix = [ halfMatrix[i] + transposedHalfMatrix[i] for i in range(numOfStates - 1) ] fullMatrix.append(halfMatrix[numOfStates - 1]) pertubationMatrix = mpmath.mp.matrix(fullMatrix) print(pertubationMatrix) energies = mpmath.mp.eigsy(pertubationMatrix, eigvals_only=True) return [float(mpmath.nstr(x)) for x in energies]
def generateRealArgument( range = [ 0, 10 ], allowNegative = True ): factor = 1 if allowNegative and getRandomInteger( 2 ) == 1: factor = -1 return nstr( fmul( exp( fmul( getRandomNumber( ), random.uniform( *range ) ) ), factor ) )
def printRealNumberAsFixed(r): assert isinstance(r, mpmath.mpf) if lessThanMaxErr(r): return '0' else: maxErrDigits = globalsettings.getSetting("maximalErrorDigits") s = mpmath.nstr(r, maxErrDigits, min_fixed = -mpmath.inf, max_fixed = mpmath.inf) a, b = s.split('.') # mpmath chops 1.2000000 to 1.2, so we are adding '0' to b alen = len(a) if a[0] in '+-': alen -= 1 b += (maxErrDigits - alen + len(b)) * '0' # b should never be more than maximalErrorDigits b = b[:maxErrDigits - alen] return a + '.' + b
def grab(self): info_dict = { 'time': time.strftime("%d.%m %H:%M:%S", time.localtime()), '24h_info': self.api.get_market_currency(self.pair), 'orders': self.api.get_order_book(self.pair), 'to_btc': False, 'converted': None } if not re.findall('BTC', self.pair): kucoin_api = api_models.KucoinApi({ 'api_key': None, 'api_secret': None, 'api_passphrase': None }) curr = re.findall('\w+', self.pair) btc_price = kucoin_api.client.get_24hr_stats(curr[0] + '-BTC')['last'] converted = nstr( mpf(info_dict['24h_info'][self.pair]['price']) * mpf(btc_price), 50)[:13] info_dict['to_btc'] = True info_dict['converted'] = converted # curr = re.findall('\w+', self.pair) # btc_curr = 'BTC-' + curr[0] # btc_price = self.api.get_market_currency(btc_curr)[btc_curr]['price'] # converted = nstr(mpf(info_dict['24h_info'][self.pair]['price']) * mpf(btc_price), 50)[:13] # info_dict['to_btc'] = True # info_dict['converted'] = converted return info_dict
def recur_rational_quadratic(x, alpha=0.5, m=1): y = [] try: for x_i in x: z = -x_i / (alpha) fz = hyp2f0(alpha, m / 2, z) ret = 2 * (1. - fz.real) ret = nstr(ret) y.append(float(ret)) except: z = -x / (alpha) fz = hyp2f0(alpha, m / 2, z) ret = 2 * (1. - fz.real) ret = nstr(ret) return float(ret) return np.array(y)
def out_mpf_C_str(self, mpf): prec = int(mpm.nstr(mpf, 0).split('e')[-1]) + 1 mpf_str = mpm.nstr(mpf, prec) mpf_int_str = mpf_str.split('.')[0] r = range(0, len(mpf_int_str), 76) + [len(mpf_int_str)] res = ' "' for i in xrange(0, len(mpf_int_str), 76): res += mpf_int_str[i:(i + 76)] if i + 78 < len(mpf_int_str): res += '\\\n ' res += '"' return res
def main(): #start the eval loop global pointer, waiting, cycles try: c = theFile[pointer] commands[c]() pointer += 1 if pointer < len(theFile) and not waiting: if cycles < 200: master.after(0, main) else: master.after(1, main) cycles = 0 cycles += 1 if options.debug: sys.stdout.write(c) if c in ['s', ',', '*']: sys.stdout.write('\n') for n in a: sys.stdout.write(mpmath.nstr(n, 4) + ", ") sys.stdout.write('\n') elif pointer >= len(theFile): #TODO:this should really be a dialog saying the program is done, rerun it or quit? master.after(3000, quit) except KeyboardInterrupt, SystemExit: print('Program terminated by user while executing instruction ' + str(pointer)) print(greporig(pointer)) quit()
def _refine_results(self, precise_intermediate_results, verbose=True): """ This step is identical to the one in Efficient enumerator. The two we're quite different in the rest of the implementation, so it didn't feel right to extend EfficientGCFEnumerator in this class. Hence, there is some code duplication here validate intermediate results to 100 digit precision :param precise_intermediate_results: list of results from first enumeration :param verbose: if true print status. :return: final results. """ results = [] counter = 0 n_iterations = len(precise_intermediate_results) for res, rhs_str, precision in precise_intermediate_results: counter += 1 if (counter % 10_000 == 0 or counter == n_iterations) and verbose: print('Passed {} permutations out of {}. Found so far {} matches'.format( counter, n_iterations, len(results))) try: all_matches = self.hash_table.evaluate(res.lhs_key) except KeyError: continue for i, match in enumerate(all_matches): # Trunc the LHS to the number of digits actually calculated. val_str = mpmath.nstr(match[0], precision + 1)[:-1] if val_str == rhs_str: results.append(RefinedMatch(*res, i, match[1], match[2], precision))
def getMPFIntegerAsString(n): '''Turns an mpmath mpf integer value into a string for use by lexicographic operators.''' if n == 0: return '0' return nstr(nint(n), int(floor(log10(n) + 10)))[:-2]
def test_enumeration_over_gcf(self): enumerator = EnumerateOverGCF([sympy.pi], 4) results = enumerator.find_hits([[0, 1, 2]] * 2, [[0, 1, 2]] * 3, print_results=False) self.assertEqual(len(results), 1) r = results[0] an = create_series_from_compact_poly(r.rhs_an_poly, 1000) bn = create_series_from_compact_poly(r.rhs_bn_poly, 1000) gcf = GeneralizedContinuedFraction(an, bn) with mpmath.workdps(100): lhs_val = mpmath.nstr(gcf.evaluate(), 50) rhs_val = enumerator.hash_table.evaluate(r.lhs_key, [mpmath.pi]) rhs_val = mpmath.nstr(rhs_val, 50) rhs_sym = enumerator.hash_table.evaluate_sym(r.lhs_key, [sympy.pi]) self.assertEqual(lhs_val, rhs_val) self.assertTrue(rhs_sym == 4 / pi)
def NumberStr(n): # Replace spaces s = n.replace(' ', '') # remove "exactly" for the carbon mass s = s.replace('(exactly)', '') # if only a number, put it three times m = bnum.match(s) if m: s = "{:<25} {:<25} {:<25}".format(m.group(1), m.group(1), m.group(1)) # if parentheses uncertainty... m = buncertain.match(s) if m: # tricky. duplicate the first part as a string s2 = m.group(1) # but replace with all zero s2 = re.sub(r'\d', '0', s2) # now replace last characters l = len(m.group(2)) s2 = s2[:len(s2)-l] + m.group(2) # convert to a float serr = mp.mpf(s2) scenter = mp.mpf(m.group(1)) s = "{:<25} {:<25} {:<25}".format(mp.nstr(scenter, 18), mp.nstr(scenter-serr, 18), mp.nstr(scenter+serr, 18)) # Replace bracketed ranges with parentheses m = brange.match(s) if m: slow = mp.mpf(m.group(1)) shigh = mp.mpf(m.group(2)) smid = (shigh + slow)/mp.mpf("2.0") s = "{:<25} {:<25} {:<25}".format(mp.nstr(smid, 18), mp.nstr(slow, 18), mp.nstr(shigh, 18)) # just a dash? if s == "-": s = "{:<25} {:<25} {:<25}".format(0, 0, 0) return s
def cstr(obj): try: return '{' + ', '.join(cstr(val) for val in obj) + '}' except TypeError: cls = type(obj) if ((cls == complex) or (cls == mpc)): return 'dynd::dynd_complex<double>({}, {})'.format(cstr(obj.real), cstr(obj.imag)) return nstr(obj, pdps)
def cstr(obj): try: return '{' + ', '.join(cstr(val) for val in obj) + '}' except TypeError: cls = type(obj) if ((cls == complex) or (cls == mpc)): return 'dynd::complex<double>({}, {})'.format(cstr(obj.real), cstr(obj.imag)) return nstr(obj, pdps)
def bradify(): """Iteratively calculates the ratios of Lucas sequence numbers. Spoiler: It approaches the golden ratio. """ argument_parser = argparse.ArgumentParser( description='Watch the ratios of numbers in a Lucas series approach ' 'the golden ratio (φ).') argument_parser.add_argument('-i', '--iterations', help='Maximum number of iterations.', type=int, default=1000) argument_parser.add_argument('-p', '--precision', help='Digits of precision to calculate', type=int, default=100) sequences = argument_parser.add_mutually_exclusive_group(required=True) sequences.add_argument('-f', '--fibonacci', dest='special_case', action='store_const', const='f', help='The Fibonacci numbers') sequences.add_argument('-l', '--lucas', dest='special_case', action='store_const', const='l', help='The Lucas numbers') sequences.add_argument('-b', '--brady', dest='special_case', action='store_const', const='b', help='The Brady numbers') sequences.add_argument('-a', type=str, dest='sequence_definition', help='A generic sequence') args = argument_parser.parse_args() if args.special_case: if args.special_case == 'f': sequence = lucas.fibo() elif args.special_case == 'l': sequence = lucas.lucas_num() elif args.special_case == 'b': sequence = lucas.brady() else: definition = args.sequence_definition.split(',') definition[0] = int(definition[0]) definition[1] = int(definition[1]) sequence = lucas.Lucas(definition, 5) mpmath.mp.dps = args.precision * 2 previous = mpmath.mpf(sequence[0]) oldphi=1000 for i in range(1, args.iterations): current = mpmath.mpf(sequence[i]) try: phi = current/previous except ZeroDivisionError: phi = float('NaN') print('φ[%d] = %s' % (i, mpmath.nstr(phi, args.precision))) if abs(oldphi - phi) < 10**(-args.precision) and i > 2: break previous = current oldphi = phi
def compose_result_string(self, mpf_x, mpf_m, n, mpf_value, output_dps): return ('{' + mp.nstr(mpf_x, output_dps * 2) + ',{' + mp.nstr(mpf_m.real, output_dps * 2) + ',' + mp.nstr(mpf_m.imag, output_dps * 2) + '},' + str(n) + ',{' + mp.nstr(mpf_value.real, output_dps) + ',' + mp.nstr(mpf_value.imag, output_dps) + '},' + mp.nstr(mp.fabs(mpf_value.real * 10**-output_dps), 2) + ',' + mp.nstr(mp.fabs(mpf_value.imag * 10**-output_dps), 2) + '},')
def mpf2float(x): """ Convert an mpf to the nearest floating point number. Just using float directly doesn't work because of results like this: with mp.workdps(50): float(mpf("0.99999999999999999")) = 0.9999999999999999 """ return float(mpmath.nstr(x, 17, min_fixed=0, max_fixed=0))
def generate_cases(): fmt = "{}{:04d} {} {!r} 0.0 -> {} 0.0" for fn in sorted(cases_to_generate.keys()): print "-- Additional real values (Jython)" count, xlist = cases_to_generate[fn] for x in xlist: func = getattr(mpmath, fn) y = func(x) print fmt.format(fn, count, fn, x, mpmath.nstr(y, 20)) count += 1
def first_digits_are_pandigital(val): val = mpmath.nstr(val,n=10) val = val.split('e') val = val[0] val = val.split('.') val = val[0]+val[1] val = val[:9] if len(set(val)) == 9 and '0' not in val: return 1 return 0
def fmt(f, inputs, out): # Here we set up output. We hope that refcounting will collect fds # promptly if out is None: out = sys.stdout else: out = open(out, 'w') for xs in inputs: param = ["%.18g" % x for x in xs] sOut = mpmath.nstr(f(*xs), mpmath.mp.dps) print('\t'.join(param + [sOut]), file=out)
def estimate( measurement ): if not isinstance( measurement, RPNMeasurement ): raise TypeError( 'incompatible type for estimating' ) unitType = None dimensions = measurement.getDimensions( ) for key, basicUnitType in g.basicUnitTypes.items( ): if dimensions == basicUnitType.dimensions: unitType = key break if unitType is None: return 'No estimates are available for this unit type' unitTypeInfo = g.basicUnitTypes[ unitType ] unit = RPNMeasurement( 1, unitTypeInfo.baseUnit ) value = RPNMeasurement( measurement.convertValue( unit ), unit.getUnits( ) ).getValue( ) if not unitTypeInfo.estimateTable: return 'No estimates are available for this unit type (' + unitType + ').' matchingKeys = [ key for key in unitTypeInfo.estimateTable if key <= value ] if matchingKeys: estimateKey = max( matchingKeys ) multiple = fdiv( value, estimateKey ) return 'approximately ' + nstr( multiple, 3 ) + ' times ' + \ unitTypeInfo.estimateTable[ estimateKey ] else: estimateKey = min( key for key in unitTypeInfo.estimateTable ) multiple = fdiv( estimateKey, value ) return 'approximately ' + nstr( multiple, 3 ) + ' times smaller than ' + \ unitTypeInfo.estimateTable[ estimateKey ]
def func(eq, x): """ Calculate the answer to f(x) Example: >>> [func([1, 0, -3, -4], i) for i in np.arange(0.0, 5.0, 1)] ['-4.0', '-6.0', '-2.0', '14.0', '48.0'] """ ans, x = mp.mpf(0), mp.mpf(str(x)) index_length = len(eq) for i in range(index_length): order = index_length - i - 1 ans = mp.fadd(ans, mp.fmul(eq[i], mp.power(x, order))) return mp.nstr(ans)
def doubledouble2string(doubdoub,n=19): """ Convert a double-double tuple into a string with n decimal digits of precision. Default is n=19, which is the maximum precision that this longdouble-based double-double format can provide. min_fixed is the position of the leading digit such that any number with a leading digit less than or equal to min_fixed will be written in exponential format. e.g., 0.00123 has its leading digit in the -3 place, so if min_fixed>=-3 it will be printed as 1.23e-3, and if min_fixed<=-4 it will be printed as 0.00123. """ mpmath.mp.prec=105 hi=mpmath.mpmathify(doubdoub[0]) lo=mpmath.mpmathify(doubdoub[1]) tot=mpmath.fadd(hi,lo) return mpmath.nstr(tot,n)
def list_zeros(N=None, t=None, limit=None, fmt=None, download=None): if N is None: N = request.args.get("N", None, int) if t is None: t = request.args.get("t", 0, float) if limit is None: limit = request.args.get("limit", 100, int) if fmt is None: fmt = request.args.get("format", "plain") if download is None: download = request.args.get("download", "no") if limit < 0: limit = 100 if N is not None: # None is < 0!! WHAT THE WHAT! if N < 0: N = 0 if t < 0: t = 0 if limit > 100000: # limit = 100000 # bread = [("L-functions", url_for("l_functions.l_function_top_page")),("Zeros of $\zeta(s)$", url_for(".zetazeros"))] return render_template('single.html', title="Too many zeros", bread=bread, kid = "dq.zeros.zeta.toomany") if N is not None: zeros = zeros_starting_at_N(N, limit) else: zeros = zeros_starting_at_t(t, limit) if fmt == 'plain': response = flask.Response(("%d %s\n" % (n, nstr(z,31+floor(log(z,10))+1,strip_zeros=False,min_fixed=-inf,max_fixed=+inf)) for (n, z) in zeros)) response.headers['content-type'] = 'text/plain' if download == "yes": response.headers['content-disposition'] = 'attachment; filename=zetazeros' else: response = str(list(zeros)) return response
def main(): print(__doc__) K = 25 N = 25 with mp.workdps(50): d = compute_d(K, N) fn = os.path.join(os.path.dirname(__file__), '..', 'cephes', 'igam.h') with open(fn + '.new', 'w') as f: f.write(header.format(K, N)) for k, row in enumerate(d): row = map(lambda x: mp.nstr(x, 17, min_fixed=0, max_fixed=0), row) f.write('{') f.write(", ".join(row)) if k < K - 1: f.write('},\n') else: f.write('}};\n') f.write(footer) os.rename(fn + '.new', fn)
def main(): print(__doc__) K = 25 N = 25 with mp.workdps(50): d = compute_d(K, N) fn = os.path.join(os.path.dirname(__file__), "..", "cephes", "igam.h") with open(fn + ".new", "w") as f: f.write(header.format(K, N)) for k, row in enumerate(d): row = map(lambda x: mp.nstr(x, 17, min_fixed=0, max_fixed=0), row) f.write("{") f.write(", ".join(row)) if k < K - 1: f.write("},\n") else: f.write("}};\n") f.write(footer) os.rename(fn + ".new", fn)
def generate_cases(): fmt = "{}{:04d} {} {!r} 0.0 -> {} {!r}" for fn in sorted(cases_to_generate.keys()): print "-- Additional real values (Jython)" count, xlist = cases_to_generate[fn] for x in xlist: # Compute the function (in the reference library) func = getattr(mpmath, fn) y = func(x) # For the benefit of cmath tests, get the sign of imaginary zero right zero = 0.0 if math.copysign(1.0, x) > 0.0: if fn == "cos": zero = -0.0 else: if fn == "cosh": zero = -0.0 # Output one test case at sufficient precision print fmt.format(fn, count, fn, x, mpmath.nstr(y, 20), zero) count += 1
def number_form(n): if rational(n): p, q = rational(n) if q == 1: if abs(n) < 2**31-1: return str(n), "i" if abs(n) < 2**63-1: return str(n), "j" else: forms, types = zip(*map(number_form, (p, q))) if all([t in ("i", "j") for t in types]): return "%".join(map(encode_item, forms, types)), "S" return number_form(p / Decimal(q)) if isinstance(n, Decimal): if abs(n) < 10 ** Decimal(-20): return "0", "f" q = abs(n).log10().quantize(1, rounding=decimal.ROUND_FLOOR) q = n.quantize(10 ** (q - 20)).as_tuple() l = len(q.digits) + q.exponent q = "-" * q.sign + \ ''.join(map(str, q.digits[:max(0, l)])) + \ "." + "0" * max(0, -l) + \ ''.join(map(str, q.digits[max(0, l):])) return q.rstrip("0").rstrip("."), "f" if isinstance(n, (mp.mpf, mp.mpc)) and not n.imag: return number_form(Decimal(mp.nstr(n.real, mp.mp.dps))) if complex_pair and isinstance(n, mp.mpc): return list_form([n.real, n.imag]) if n is None: return "0n", "f" raise Exception()
def formattedFloatString(val, dps): if QSMODE == MODE_NORM: return ("{:1."+str(dps)+"f}").format(val) else: return mpmath.nstr(val, mpIntDigits(val)+dps)
def xs( data , energy , cep , sep ): '''This function will determine photon cross sections''' sep() logging.debug( 'Entering the xs function' ) #Init the storage array cs_array = np.zeros( 3 ) #Here we define the concreate density rho = 2.3 #Here we define a rough electron density e_den = mp.mpf( 3 * 10**( 23 ) * 100**3 ) #Here we define the speed of light, planks const, and electron mass plank = mp.mpf( 6.626 * 10**( -34 ) ) qo = mp.mpf( 1.602 * 10**( -19 ) ) light = mp.mpf( 3.0 * 10**( 8 ) ) mass = mp.mpf( 9.109 * 10**( -31 ) ) #Set the energy as an extended precision number eng = mp.mpmathify( energy ) eng = eng * 10**( -13 ) #Get the frequency v = eng / plank #This is a fudge factor to get the compton xs to be close to realistic f = 10**(31) #Here we calculate the compton cross section radius = qo**4 / ( mass * light**2 ) alpha = ( eng ) / ( mass * light**2 ) cs_xs = 2 * mp.pi * radius * ( ( ( 1.0 + alpha ) \ / ( alpha**2 ) ) * ( ( ( 2.0 * ( 1.0 + alpha ) \ ) / ( 1.0 + 2.0 * alpha ) ) - ( 1.0 / alpha ) * \ ( mp.log( 1.0 + 2.0 * alpha ) ) ) + ( ( 1.0 / \ ( 2.0 * alpha ) ) * mp.log( 1.0 + 2.0 * alpha ) - \ ( ( 1.0 + 3.0 * alpha ) / ( 1.0 + 2.0 * alpha )**2 ) ) ) cep() logging.debug( 'The micro cs xs is: ' + mp.nstr( \ cs_xs , n = 10 ) ) mu_cs = cs_xs * e_den * f logging.debug( 'The macro cs xs is: ' + mp.nstr( \ mu_cs , n = 10 ) ) cs_array[ 1 ] = float( mp.nstr( mu_cs , n = 10 ) ) #Now we will determine, via linear interp, the total xs cep() logging.debug( 'Energy of photon is: ' + str( energy ) ) if energy <= data[ 0 , 0 ]: logging.debug( 'Lowest energy point is: ' + \ str( data[ 0 , 0 ] ) ) logging.debug( 'Xs at lowest energy is: ' + \ str( data[ 0 , 1 ] ) ) cs_array[ 0 ] = ( ( data[ 1 , 1 ] - data[ 0 , 1 ] ) \ ( data[ 1 , 0 ] - data[ 0 , 0 ] ) ) * ( \ data[ 0 , 0 ] - energy ) - data[ 0 , 1 ] logging.debug( 'Calculated XS is: ' + \ str( cs_array[ 0 ] ) ) else: for row in range( len( data ) - 1 ): index = row + 1 if energy <= data[ index , 0 ]: logging.debug( 'Energy of photon is: '\ + str( energy ) ) logging.debug( 'Energy of lower XS is: ' \ + str( data[ index - 1 , 0 ] ) ) logging.debug( 'Energy of higher XS is: ' \ + str( data[ index , 0 ] ) ) logging.debug( 'Lower XS is: ' + \ str( data[ index -1 , 1 ] ) ) logging.debug( 'Higher XS is: ' + str( data[ index , 1 ] ) ) cs_array[ 0 ] = ( ( data[ index , 0 ] - \ data[ index - 1 , 0 ] ) / ( \ data[ index , 1 ] - data[ index - 1 , 1 ] \ ) ) * ( data[ index , 0 ] - energy ) + \ data[ index -1 , 1 ] logging.debug( 'Calculated XS is: ' + \ str( cs_array[ 0 ] ) ) break #Multiply by rho cs_array[ 0 ] = cs_array[ 0 ] * rho cs_array[ 2 ] = cs_array[ 0 ] - cs_array[ 1 ] cep() logging.debug( 'The cs_array is: ' + str( cs_array ) ) logging.debug( 'Leaving the xs function' ) sep() return( cs_array )
IRRATIONALS = [ mp.phi, mp.pi, mp.e, mp.euler, mp.apery, mp.log(mp.pi), ] +\ [ abs(transform(prime))\ for (prime, transform) in product(PRIMES, TRANSFORMS) ] SEEDS = [] for num in IRRATIONALS: inv = 1/num seed1 = mp.nstr(num, mp.mp.dps).replace('.', '') seed2 = mp.nstr(inv, mp.mp.dps).replace('.', '') for precision in PRECISIONS: SEEDS.append(seed1[:precision]) SEEDS.append(seed2[:precision]) if num >= 1: seed3 = mp.nstr(num, mp.mp.dps).split('.')[1] for precision in PRECISIONS: SEEDS.append(seed3[:precision]) continue if inv >= 1: seed4 = mp.nstr(inv, mp.mp.dps).split('.')[1] for precision in PRECISIONS: SEEDS.append(seed4[:precision])
def handleOutput( valueList, indent=0, file=sys.stdout ): ''' Once the evaluation of terms is complete, the results need to be translated into output. It is expected there will be a single result, otherwise an error is thrown because the expression was incomplete. If the result is a list or a generator, special formatting turns those into text output. Date-time values and measurements also require special formatting. Setting file to an io.StringIO objects allows for 'printing' to a string, which is used by makeHelp.py to generate actual rpn output for the examples. ''' if valueList is None: return file indentString = ' ' * indent if len( valueList ) != 1: valueList = [ valueList ] if isinstance( valueList[ 0 ], RPNFunction ): print( indentString + 'rpn: unexpected end of input in function definition', file=file ) else: mp.pretty = True result = valueList.pop( ) if result is nan: return file if g.comma: g.integerGrouping = 3 # override whatever was set on the command-line g.leadingZero = False # this one, too g.integerDelimiter = ',' else: g.integerDelimiter = ' ' if isinstance( result, RPNGenerator ): formatListOutput( result.getGenerator( ), indent=indent, file=file ) elif isinstance( result, list ): formatListOutput( result, indent=indent, file=file ) else: if isinstance( result, RPNVariable ): result = result.getValue( ) elif isinstance( result, RPNDateTime ): outputString = formatDateTime( result ) elif isinstance( result, str ): result = checkForVariable( result ) outputString = result else: # output the answer with all the extras according to command-line arguments # handle the units if we are displaying a measurement if isinstance( result, RPNMeasurement ): outputString = formatOutput( nstr( result.getValue( ), mp.dps, min_fixed=-g.maximumFixed - 1 ) ) outputString += ' ' + formatUnits( result ) else: outputString = formatOutput( nstr( result, mp.dps, min_fixed=-g.maximumFixed - 1 ) ) print( indentString + outputString, file=file ) # handle --identify if g.identify: handleIdentify( result, file ) saveResult( result ) if g.timer or g.tempTimerMode: print( '\n' + indentString + '{:.3f} seconds'.format( time.process_time( ) - g.startTime ), file=file )