本文整理汇总了Python中mpmath.nstr函数的典型用法代码示例。如果您正苦于以下问题:Python nstr函数的具体用法?Python nstr怎么用?Python nstr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了nstr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: mpf_assert_allclose
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))
示例2: add_gwb
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()
示例3: savetim
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()
示例4: output
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
示例5: test_nstr
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]
示例6: pariDilog
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'))
示例7: main
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()
示例8: printRealNumberAsFixed
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
示例9: generateRealArgument
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 ) )
示例10: NumberStr
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
示例11: cstr
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)
示例12: bradify
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
示例13: first_digits_are_pandigital
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
示例14: mpf2float
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))
示例15: func
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)