Example #1
0
def CalibrationHa(z,oldLum,it):
	newLum = [0. for x in range((it.shape[0]))]
	oldpara = np.array([[0. for i in range(3)] for i in range(it.shape[0])])
	oldLF = np.array([0. for i in range(it.shape[0])])
	interpolatingSize =100
	for i in range(oldpara.shape[0]):
	        oldpara[i][0] = 1.37e-3
	        oldpara[i][2] = -1.35
	        if z[it[i]] <1.3 :oldpara[i][1] = 5.1e41*np.power((1+z[it[i]]),3.1)
	        if z[it[i]] >=1.3:oldpara[i][1] =6.8e42
	        oldLF[i] = LuminosityFunction(oldpara[i],oldLum[i])
	rangea = oldLF.copy()
	rangea.sort()
	rangea = rangea[rangea>0]
	grid = np.array([[0. for i in range(interpolatingSize)] for i in range(2)])
	mpgrid = mpmath.arange(mpmath.log10(rangea.min()),mpmath.log10(rangea.max()),(np.log10(rangea.max())-np.log10(rangea.min()))/interpolatingSize)
	grid[0] = np.ogrid[np.log10(rangea.min()):np.log10(oldLF.max()):interpolatingSize*1j]
	grid[1] = np.ogrid[0:6:interpolatingSize*1j]
	newLF = np.array([[0.for i in range(interpolatingSize)] for i in range(interpolatingSize)])
	for i in range(interpolatingSize):
		for j in range(interpolatingSize):
			newLF[i][j]= optimize.brentq(rootfinding,1e30,1e50,args=(luminosityParameterHa(grid[1][i]),mpgrid[j]))
	newLum = interpolate.interpn([grid[0],grid[1]],newLF,np.array([np.log10(oldLF),z[it]]).T,bounds_error=False,fill_value=0.0)
	newLum = np.power(10,newLum)
	return newLum
def calculate_convergence(gcf: GeneralizedContinuedFraction,
                          reference,
                          plot=False,
                          title=''):
    """
    calculate convergence rate of General Continued Fraction (in reference to some constant x).
    the result is the average number of decimal digits, per term of the general continued fraction.
    :param plot: whether or not to plot the graph of the log10 difference between convergent and x.
    :param gcf: General Continued Fraction to calculate.
    :param title: (optional) title of graph.
    :param reference: x
    """
    q_ = [0, 1]
    p_ = [1, gcf.a_[0]]
    log_diff = [mpmath.log10(abs((dec(p_[1]) / dec(q_[1])) - reference))]
    length = min(200, len(gcf.b_))
    for i in range(1, length):
        q_.append(gcf.a_[i] * q_[i] + gcf.b_[i - 1] * q_[i - 1])
        p_.append(gcf.a_[i] * p_[i] + gcf.b_[i - 1] * p_[i - 1])
        if q_[i + 1] == 0:
            part_convergent = 0
        else:
            part_convergent = dec(p_[i + 1]) / dec(q_[i + 1])
        if not mpmath.isfinite(part_convergent):
            length = i
            break
        log_diff.append(mpmath.log10(abs(part_convergent - reference)))
    if plot:
        plt.plot(range(length), log_diff)
        plt.title(title)
        plt.show()
    log_slope = 2 * (log_diff[length - 1] - log_diff[length // 2]) / length
    return -log_slope
Example #3
0
def p(L, n):

    C = mp.log10(2)
    po = mp.mp.power(10, mp.floor(mp.log10(L)))
    C1 = mp.log10(mp.mpf(L) / po)
    C2 = mp.log10(mp.mpf(L + 1) / po)
    k = 1

    while not (C1 <= mp.frac(k * C) < C2):
        k += 1
        auxi = lambda k: mp.frac(k * C) - C1

    approximators = add_approximators(1000, C)
    curr = (k, auxi(k))
    treshold = mp.log10(mp.mpf(L + 1) / mp.mpf(L))
    idx = 1
    while idx < n:
        for el in approximators:
            if 0 <= curr[1] + el[1] < treshold:

                curr = (curr[0] + el[0], auxi(curr[0] + el[0]))
                idx += 1
                #print(curr[0], idx)
                break
    return curr[0]
Example #4
0
 def __compute_surprise_weighted(self, mi, pi, m, p):
     b1 = mpmath.binomial(pi, mi)
     b2 = mpmath.binomial(p - pi, m - mi)
     b3 = mpmath.binomial(p, m)
     h3f2 = mpmath.hyp3f2(1, mi - m, mi - pi, mi + 1, -m + mi + p - pi + 1,
                          1)
     #h3f2 = hyper1([mpf(1),mi-m, mi-pi], [mpf(1),mpf(1)+mi, mi+p-pi-m+mpf(1)], 10, 10)
     log10cdf = mpmath.log10(b1) + mpmath.log10(b2) + mpmath.log10(
         h3f2) - mpmath.log10(b3)
     return -float(log10cdf)
Example #5
0
 def __call__(self, event):
     if event.button == 2:
         new_x_lim = self.axes.get_xlim()
         re_span = self.re_lim[1] - self.re_lim[0]
         new_re_lim = (new_x_lim[0] / res[0] * re_span + self.re_lim[0], 
                       new_x_lim[1] / res[0] * re_span + self.re_lim[0])
         
         new_y_lim = self.axes.get_ylim()
         im_span = self.im_lim[1] - self.im_lim[0]
         new_im_lim = (new_y_lim[0] / res[1] * im_span + self.im_lim[0],
                       new_y_lim[1] / res[1] * im_span + self.im_lim[0])
         
         new_re_span = new_re_lim[1] - new_re_lim[0]
         new_im_span = new_im_lim[1] - new_im_lim[0]
         
         print(int(mpmath.log10(1/new_re_span))+1, int(mpmath.log10(1/new_im_span))+1)
         
         dps = max([int(mpmath.log10(1/new_re_span))+1, int(mpmath.log10(1/new_im_span))+1]) + int(mpmath.log10(max(res))) + 1
         mpmath.mp.dps = dps
         print(mpmath.mp)
         
         mset = brot_gen_parallel(new_re_lim, new_im_lim, 1000000)
         
         self.axes.cla()
         self.axes.imshow(mset, origin="lower", vmin=-0.1, cmap=colmap, interpolation="bilinear")
         
         self.canvas.draw()
         
         self.re_lim = new_re_lim
         self.im_lim = new_im_lim
     else:
         if event.button == 'up':
             scale_factor = 1 / base_factor
             self.depth *= base_factor
         elif event.button == 'down':
             scale_factor = base_factor
             self.depth /= base_factor
         else:
             return
         
         cur_xlim = ax.get_xlim()
         cur_ylim = ax.get_ylim()
         xdata = event.xdata # get event x location
         ydata = event.ydata
         xlim = [xdata - (xdata - cur_xlim[0])*scale_factor,
                 xdata + (cur_xlim[1] - xdata)*scale_factor]
         ylim = [ydata - (ydata - cur_ylim[0])*scale_factor,
                 ydata + (cur_ylim[1] - ydata)*scale_factor]
         self.axes.set_xlim(xlim[0], xlim[1])
         self.axes.set_ylim(ylim[0], ylim[1])
         self.canvas.draw()
Example #6
0
def fmin_gd(f,
            f_dx=None,
            x_0=1,
            alpha=0,
            error=1e-10,
            max_iter=1e+5,
            alpha_mul=1,
            disp=True):
    '''
	Uses gradient descent algorithm to find a *univariate* function's minimum
	Based on mpmath
	returns x where f(x) is minimized

	f - function to minimize. must only take in x as a parameter
	f_dx - optional, first derivative of f
	x_0 - optional, initial value of x
	alpha - optional, learning rate
	error - optional, acceptable error threshold
	max_iter - optional, maximum iterations
	alpha_mul - optional, multiplier to heuristically determined alpha
	disp - optional, prints out Iterations and Final Step if True

	Reference: https://en.wikipedia.org/wiki/Gradient_descent#Python
	'''
    if f_dx is None: f_dx = lambda x: mp.diff(f, x)

    # heuristically determine learning rate
    if alpha == 0:
        try:
            alpha = alpha_mul * mp.power(
                10, -2 - int(mp.log10(abs(f(x_0)) / abs(x_0))))
        except:
            alpha = alpha_mul * mp.power(
                10, -2 - int(mp.log10(abs(f(x_0 + 0.1)) / abs((x_0 + 0.1)))))

    cur_x = x_0
    step = alpha * f_dx(cur_x)
    ctr = 0
    while abs(step) > abs(error):
        step = alpha * f_dx(cur_x)
        cur_x -= step
        ctr += 1
        if ctr >= max_iter:
            warnings.warn(
                "Gradient Descent exited due to max iterations %i.\nReview alpha or x_0."
                % (max_iter))
            break
    if disp: print('Iterations: %i\nFinal Step Size: %.2e' % (ctr, step))
    return cur_x
Example #7
0
 def __compute_surprise_weighted_by_quadrature(self, mi, pi, m, p):
     f = lambda i: mpmath.binomial(
         self.pi, i) * mpmath.binomial(self.p - self.pi, self.m - i) / \
         mpmath.binomial(self.p, self.m)
     # +- 0.5 is because of the continuity correction
     return float(
         -mpmath.log10(mpmath.quad(f, [self.mi - 0.5, self.m + 0.5])))
Example #8
0
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 ]
Example #9
0
 def __call__(self,t):
 
   with mp.extradps(self.prec):
     t = mpf(t)
     if t == 0:
       print "ERROR:   Inverse transform can not be calculated for t=0"
       return ("Error");
           
     N = 2*self.N
     # Initiate the stepsize (mit aktueller Präsision)
     h = 2*pi/N
  
   # The for loop is evaluating the Laplace inversion at each point theta i
   #   which is based on the trapezoidal rule
     ans =  0.0
     for k in range(self.N):
       theta = -pi + (k+0.5)*h
       z = self.shift + N/t*(Talbot.c1*theta/tan(Talbot.c2*theta) - Talbot.c3 + Talbot.c4*theta)
       dz = N/t * (-Talbot.c1*Talbot.c2*theta/sin(Talbot.c2*theta)**2 + Talbot.c1/tan(Talbot.c2*theta)+Talbot.c4)
       v1 = exp(z*t)*dz
       prec = floor(max(log10(abs(v1)),0))
       with mp.extradps(prec):
         value = self.F(z)
       ans += v1*value
           
     return ((h/pi)*ans).imag
Example #10
0
def sig_figs_jy(jn, jn1, yn, yn1, z):
    """Check relation http://dlmf.nist.gov/10.50 .

    Parameters
    ----------
        jn : mpf
            The value of j_n(x).
        jn1 : mpf
            The value of j_{n + 1}(x).
        yn : mpf
            The value of y_n(x).
        yn1 : mpf
            The value of y_{n + 1}(x).

    Returns
    -------
    The estimated number of significant digits to which the computation of
    the passed Bessel functions is correct.

    """
    w = mpmath.fabs(z**2 * (jn1 * yn - jn * yn1) - 1)
    if not mpmath.isfinite(w):
        return w
    if w > 0:
        return 1 - mpmath.log10(w)
    else:
        return mpmath.mp.dps
Example #11
0
def sig_figs_jy(jn, jn1, yn, yn1, z):
    """Check relation http://dlmf.nist.gov/10.50 .

    Parameters
    ----------
        jn : mpf
            The value of j_n(x).
        jn1 : mpf
            The value of j_{n + 1}(x).
        yn : mpf
            The value of y_n(x).
        yn1 : mpf
            The value of y_{n + 1}(x).

    Returns
    -------
    The estimated number of significant digits to which the computation of
    the passed Bessel functions is correct.

    """
    w = mpmath.fabs(z**2*(jn1*yn - jn*yn1) - 1)
    if not mpmath.isfinite(w):
        return w
    if w > 0:
        return 1 - mpmath.log10(w)
    else:
        return mpmath.mp.dps
Example #12
0
def single_segment_expect_pv(expect, raw=True):
    """
    Compute p-value for an expect value of
    a single high scoring segment.

    Prob(E >= x) ~ 1 - exp(-E)

    This function is equivalent to
    single_segment_score_pv
    as long as identical units (log)
    are used to compute scores and expect

    :param expect:
    :param raw: return raw P-value instead of -log10(pv)
    :return:
    """
    with mpm.workprec(NUM_PREC_KA_PV):
        x = mpm.convert(expect)
        complement = mpm.convert('1')
        res = mpm.fsub(complement, mpm.exp(mpm.fneg(x)))
        if not raw:
            res = mpm.fneg(mpm.log10(res))
            res = float(res)

    return res
Example #13
0
def single_segment_score_pv(score, raw=True):
    """
    Compute p-value for normalized local score of
    a single high scoring segment.

    Computes formula [1] in Karlin & Altschul, PNAS 1993

    Prob(S' >= x) ~ 1 - exp(-exp(-x))

    :param score:
    :param raw: return raw P-value instead of -log10(pv)
    :return:
    """
    with mpm.workprec(NUM_PREC_KA_PV):
        x = mpm.convert(score)
        complement = mpm.convert('1')
        exponent = mpm.fneg(mpm.exp(mpm.fneg(x)))
        res = mpm.fsub(complement, mpm.exp(exponent))
        if not raw:
            res = mpm.fneg(mpm.log10(res))
            res = float(res)

    # Equivalent implementation using Python standard library:
    #
    # x = score
    # res = 1 - math.exp(-math.exp(-x))
    # if not raw:
    #     res = -1 * math.log10(res)
    return res
Example #14
0
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 relative_directivity_db(angle,k_v,R_v,alpha_v,An):
    '''Calculates on-axis and off-axis angles to get the directivity
    for piston in a sphere.
    '''
    off_axis = d_theta(angle,k_v,R_v,alpha_v,An)
    on_axis = d_zero(k_v,R_v,alpha_v,An)
    rel_level = 20*mpmath.log10(np.abs(off_axis/on_axis))
    return rel_level
Example #16
0
def runYAFU(n):
    fullOut = subprocess.run([
        g.userConfiguration['yafu_path'] + os.sep +
        g.userConfiguration['yafu_binary'], '-xover', '120'
    ],
                             input='factor(' + str(int(n)) + ')\n',
                             encoding='ascii',
                             stdout=subprocess.PIPE,
                             cwd=g.userConfiguration['yafu_path'],
                             check=True).stdout

    #print( 'out', fullOut )

    out = fullOut[fullOut.find('***factors found***'):]

    if len(out) < 2:
        if log10(n) > 40:
            raise ValueError('yafu seems to have crashed trying to factor ' +
                             str(int(n)) + '.\n\nyafu output follows:\n' +
                             fullOut)

        debugPrint(
            'yafu seems to have crashed, switching to built-in factoring code')
        return factorise(int(n))

    result = []

    while True:
        prime = ''

        out = out[out.find('P'):]

        if len(out) < 2:
            break

        out = out[out.find('='):]

        index = 2

        while out[index] >= '0' and out[index] <= '9':
            prime += out[index]
            index += 1

        result.append(mpmathify(prime))

    if not result:
        raise ValueError('yafu seems to have failed.')

    answer = fprod(result)

    if answer != n:
        debugPrint('\nyafu has barfed')
        for i in result:
            n = fdiv(n, i)

        result.extend(runYAFU(n))

    return sorted(result)
Example #17
0
def getECMFactors( target ):
    from pyecm import factors

    n = int( floor( target ) )

    verbose = g.verbose
    randomSigma = True
    asymptoticSpeed = 10
    processingPower = 1.0

    if n < -1:
        return [ ( -1, 1 ) ] + getECMFactors( fneg( n ) )
    elif n == -1:
        return [ ( -1, 1 ) ]
    elif n == 0:
        return [ ( 0, 1 ) ]
    elif n == 1:
        return [ ( 1, 1 ) ]

    if verbose:
        print( '\nfactoring', n, '(', int( floor( log10( n ) ) ), ' digits)...' )

    if g.factorCache is None:
        loadFactorCache( )

    if n in g.factorCache:
        if verbose and n != 1:
            print( 'cache hit:', n )
            print( )

        return g.factorCache[ n ]

    result = [ ]

    for factor in factors( n, verbose, randomSigma, asymptoticSpeed, processingPower ):
        result.append( factor )

    result = [ int( i ) for i in result ]

    largeFactors = list( collections.Counter( [ i for i in result if i > 65535 ] ).items( ) )
    product = int( fprod( [ power( i[ 0 ], i[ 1 ] ) for i in largeFactors ] ) )

    save = False

    if product not in g.factorCache:
        g.factorCache[ product ] = largeFactors
        save = True

    result = list( collections.Counter( result ).items( ) )

    if n > g.minValueToCache and n not in g.factorCache:
        g.factorCache[ n ] = result
        g.factorCacheIsDirty = True

    if verbose:
        print( )

    return result
Example #18
0
def addDigits(n, k):
    digits = int(k)

    if digits == 0:
        digitCount = 1
    else:
        digitCount = int(fadd(floor(log10(k)), 1))

    return appendDigits(n, digits, digitCount)
Example #19
0
    def get_ratios(self):
        if self._ratio == None:
            self.check()
            self._ratio = []

            for i in range(len(self._second_distances)):
                if self._first_distances[i] != None and self._second_distances[
                        i] != None:
                    if self._second_distances[i] >= self._first_distances[i]:
                        self._ratio.append(
                            mpmath.log10(self._second_distances[i] /
                                         self._first_distances[i]))
                    else:
                        self._ratio.append(
                            -mpmath.log10(self._first_distances[i] /
                                          self._second_distances[i]))

        return self._ratio
Example #20
0
def relative_directivity_db(angle, k_v, R_v, alpha_v):
    '''
    Calculates the :math:`D_{\\theta}/D_{0}` in dB for all angles
    in the cap in a sphere model.
    '''
    off_axis = d_theta(k_v, R_v, alpha_v, angle)
    on_axis = d_zero(k_v, R_v, alpha_v)
    rel_level = 20*mpmath.log10(abs(off_axis/on_axis))
    return rel_level
Example #21
0
    def test(self,do_twoy=False,up_to_M=0):
        r""" Return the number of digits we believe are correct (at least) 

        EXAMPLES::

        
            sage: G=MySubgroup(Gamma0(1))
            sage: R=mpmath.mpf(9.53369526135355755434423523592877032382125639510725198237579046413534)
            sage: F=MaassWaveformElement(G,R)    
            sage: F.test()
            7



        """
        # If we have a Gamma_0(N) we can use Hecke operators
        if(not do_twoy and (isinstance(self._space,sage.modular.arithgroup.congroup_gamma0.Gamma0_class) or \
            self._space._G.is_congruence)):
            # isinstance(self._space,sage.modular.arithgroup.congroup_sl2z.SL2Z_class_with_category))):
            if(self._space._verbose>1):
                print "Check Hecke relations!"
            er=test_Hecke_relations(2,3,self.coeffs)
            d=floor(-mpmath.log10(er))
            if(self._space._verbose>1):
                print "Hecke is ok up to ",d,"digits!"
            return d
        else:
            # Test two Y's
            nd=self._nd+5
            [M0,Y0]=find_Y_and_M(G,R,nd)
            Y1=Y0*0.95
            C1=Maassform_coeffs(self,R,Mset=M0,Yset=Y0 ,ndigs=nd )[0]
            C2=Maassform_coeffs(self,R,Mset=M0,Yset=Y1 ,ndigs=nd )[0]
            er=mpmath.mpf(0)
            for j in range(2,max(M0/2,up_to_M)):
                t=abs(C1[j]-C2[j])
                print "|C1-C2[",j,"]|=|",C1[j],'-',C2[j],'|=',t
                if(t>er):
                    er=t
            d=floor(-mpmath.log10(er))
            print "Hecke is ok up to ",d,"digits!"
            return d
Example #22
0
def compareLists(result1, result2):
    if len(result1) != len(result2):
        raise ValueError('lists are not of equal length:', len(result1),
                         len(result2))

    for i in range(0, len(result1)):
        if isinstance(result1[i], RPNGenerator):
            return compareLists(list(result1[i].getGenerator()), result2[i])

        if isinstance(result2[i], RPNGenerator):
            return compareResults(result1[i], list(result2[i].getGenerator()))

        if isinstance(result1[i], list) != isinstance(result2[i], list):
            raise ValueError('lists are nested to different levels:', result1,
                             result2)

        if isinstance(result1[i], list) and isinstance(result2[i], list):
            compareLists(result1[i], result2[i])
        else:
            if isinf(result1[i]):
                if isinf(result2[i]):
                    return True
                else:
                    print('**** error in results comparison')
                    print(type(result1[i]), type(result2[i]))
                    print(result1[i], result2[i], 'are not equal')

                    raise ValueError('unit test failed')

            if not compareValues(result1[i], result2[i]):
                digits = max(log10(result1[i]), log10(result2[i])) + 5

                mp.dps = digits

                print('**** error in results comparison')
                print(type(result1[i]), type(result2[i]))
                print(result1[i], result2[i], 'are not equal')
                print('difference', fsub(result1[i], result2[i]))
                print('difference found at index', i)

                raise ValueError('unit test failed')
    return True
Example #23
0
 def G(self,s): # Laplace-Transform
   zz = 2*self.v + 2 + s
   mu = sqrt(self.v**2+2*zz)
   a  = mu/2 - self.v/2 - 1
   b  = mu/2 + self.v/2 + 2
   v1 = (2*self.alp)**(-a)*gamma(b)/gamma(mu+1)/(zz*(zz - 2*(1 + self.v)))
   prec = floor(max(log10(abs(v1)),mp.dps))+self.prec
   # additional precision needed for computation of hyp1f1
   with mp.extradps(prec):
     value = hyp1f1(a,mu + 1,self.beta)*v1
   return value
Example #24
0
def getFactors(target):
    if target < -1:
        result = [-1]
        result.extend(getFactors(fneg(target)))
        return result

    if target == -1:
        return [-1]

    if target == 0:
        return [0]

    if target == 1:
        return [1]

    n = int(floor(target))

    setAccuracy(floor(fadd(log10(n), 2)))

    if g.factorCache is None:
        loadFactorCache()

    if not g.ignoreCache:
        if n in g.factorCache:
            if g.verbose and n != 1:
                print('cache hit:', n)
                print()

            debugPrint('\nfactor cache', n, g.factorCache[n])

            return g.factorCache[n]

    try:
        result = factorByTrialDivision(n)  # throws if n is too big

        if n > g.minValueToCache and n not in g.factorCache:
            g.factorCache[n] = result

        return result

    except ValueError:
        pass

    if g.useYAFU and n > g.minValueForYAFU:
        result = runYAFU(n)
    else:
        result = factorise(int(n))

    if n > g.minValueToCache:
        if g.ignoreCache or (not g.ignoreCache and n not in g.factorCache):
            debugPrint('\ncaching factors of ', n, result)
            g.factorCache[n] = result

    return result
Example #25
0
def brute_force(N):
    '''
    Just to test the actual function
    '''
    k = 1
    idx = 0
    for i in range(N):
        if str(k)[:3] == str(L):
            idx += 1
            print(mp.nstr(mp.log10(k) / C), idx)
        k *= 2
Example #26
0
    def publish_drawing_rect(self):
        print("------*----- publish zoom")
        if self._qim is None:
            return
#        print("publish", self._rect_pos0, self._rect_pos1)
#        print("fractal", self._presenter["fractal"])
#        print("fractal", self._presenter["image"])
        nx = self._fractal_zoom_init["nx"]
        ny = self._fractal_zoom_init["ny"]
        # new center offet in pixel
        center_off_px = 0.5 * (self._rect_pos0.x() + self._rect_pos1.x() - nx)
        center_off_py = 0.5 * (ny - self._rect_pos0.y() - self._rect_pos1.y())
        dx_pix = abs(self._rect_pos0.x() - self._rect_pos1.x())
#        print("center px", center_off_px)
#        print("center py", center_off_py)
        ref_zoom = self._fractal_zoom_init.copy()
        # str -> mpf as needed
        to_mpf = {k: isinstance(self._fractal_zoom_init[k], str) for k in
                  ["x", "y", "dx"]}
        # We may need to increase the dps to hold sufficent digits
        if to_mpf["dx"]:
            ref_zoom["dx"] = mpmath.mpf(ref_zoom["dx"])
        pix = ref_zoom["dx"] / float(ref_zoom["nx"])
        with mpmath.workdps(6):
            # Sets the working dps to 10e-8 x pixel size
            ref_zoom["dps"] = int(-mpmath.log10(pix * dx_pix / nx) + 8)
        print("------*----- NEW dps from zoom", ref_zoom["dps"])

#        if ref_zoom["dps"] > mpmath.dps:
#        zoom_dps = max(ref_zoom["dps"], mpmath.mp.dps)
        with mpmath.workdps(ref_zoom["dps"]):
            for k in ["x", "y"]:
                if to_mpf[k]:
                    ref_zoom[k] = mpmath.mpf(ref_zoom[k])
    
    #        print("is_mpf", to_mpf, ref_zoom)
    
            ref_zoom["x"] += center_off_px * pix
            ref_zoom["y"] += center_off_py * pix
            ref_zoom["dx"] = dx_pix * pix
    
            
            
            #  mpf -> str (back)
            for (k, v) in to_mpf.items():
                if v:
                    if k == "dx":
                        ref_zoom[k] = mpmath.nstr(ref_zoom[k], 16)
                    else:
                        ref_zoom[k] = str(ref_zoom[k])

        for key in ["x", "y", "dx", "dps"]:
            self._presenter[key] = ref_zoom[key]
Example #27
0
def runYAFU( n ):
    import subprocess

    full_out = subprocess.run( [ g.userConfiguration[ 'yafu_path' ] + os.sep +
                                 g.userConfiguration[ 'yafu_binary' ], str( int( n ) ), '-xover', '120' ],
                             stdout=subprocess.PIPE, cwd=g.userConfiguration[ 'yafu_path' ] ).stdout.decode( 'ascii' )

    #print( 'out', full_out )

    out = full_out[ full_out.find( '***factors found***' ) : ]

    if len( out ) < 2:
        if log10( n ) > 40:
            raise ValueError( 'yafu seems to have crashed trying to factor ' + str( int( n ) ) +
                              '.\n\nyafu output follows:\n' + full_out )
        else:
            debugPrint( 'yafu seems to have crashed, switching to built-in factoring code' )
            from rpn.factorise import factorise
            return factorise( int( n ) )

    result = [ ]

    while True:
        prime = ''

        out = out[ out.find( 'P' ) : ]

        if len( out ) < 2:
            break

        out = out[ out.find( '=' ) : ]

        index = 2

        while out[ index ] >= '0' and out[ index ] <= '9':
            prime += out[ index ]
            index += 1

        result.append( mpmathify( prime ) )

    if not result:
        raise ValueError( 'yafu seems to have failed.' )

    answer = fprod( result )

    if answer != n:
        debugPrint( '\nyafu has barfed' )
        for i in result:
            n = fdiv( n, i )

        result.extend( runYAFU( n ) )

    return sorted( result )
Example #28
0
def addDigits( n, k ):
    if real( k ) < 0:
        raise ValueError( "'add_digits' requires a non-negative integer for the second argument" )

    digits = int( k )

    if digits == 0:
        digitCount = 1
    else:
        digitCount = int( fadd( floor( log10( k ) ), 1 ) )

    return appendDigits( n, digits, digitCount )
Example #29
0
    def log10sumexp(self, log10_array):
        '''
        return value approxiameting to log10(sum(10^log10_probs))
        '''

        if (self.speedUp):

            n_array = self.ffi.cast("int", len(log10_array))
            log10_array_c = self.ffi.new("double []", log10_array)
            return self.lib.log10sumexp(log10_array_c, n_array)

        m = max(log10_array)
        return m + math.log10(sum(pow(10.0, x - m) for x in log10_array))
Example #30
0
def multi_segment_score_pv(score, num_segments, raw=True):
    """
    Compute p-value for normalized score when considering
    multiple high scoring segments. This functions considers
    the normalized score Sr', i.e., the normalized score
    of the HSP at rank r. For r=1, this formula is equivalent
    to single_segment_score_pv

    Computes formula [3] in Karlin & Altschul, PNAS 1993

    Prob(Sr' >= x) ~ 1 - exp(-exp(-x)) * SUM (k=0 ... r - 1) { exp(-kx) / k! }

    Implementation detail:
    Python's range is not right-inclusive,
    go up to r, not r - 1 for summation

    :param score:
    :param num_segments:
    :param raw: return raw P-value instead of -log10(pv)
    :return:
    """

    with mpm.workprec(NUM_PREC_KA_PV):

        def create_summand(sum_x, k):
            prec_k = mpm.convert(k)
            enum = mpm.exp(mpm.fneg(mpm.fmul(prec_k, sum_x)))
            denom = mpm.factorial(prec_k)
            summand = mpm.fdiv(enum, denom)
            return summand

        x = mpm.convert(score)
        r = num_segments
        complement = mpm.convert('1')
        factor1 = mpm.exp(mpm.fneg(mpm.exp(mpm.fneg(x))))
        factor2 = mpm.fsum(map(lambda k: create_summand(x, k), range(0, r)))
        res = mpm.fsub(complement, mpm.fmul(factor1, factor2))
        if not raw:
            res = mpm.fneg(mpm.log10(res))
            res = float(res)

    # Equivalent implementation using Python standard library:
    #
    # x = score
    # r = num_segments
    # factor_1 = math.exp(-math.exp(-x))
    # factor_2 = math.fsum(map(lambda k: math.exp(-k * x) / math.factorial(k), range(0, r)))
    # res = 1 - factor_1 * factor_2
    # if not raw:
    #     res = -1 * math.log10(res)
    return res
Example #31
0
def getPartitionNumber( n ):
    '''
    This version is, um, less recursive than the original, which I've kept.
    The strategy is to create a list of the smaller partition numbers we need
    to calculate and then start calling them recursively, starting with the
    smallest.  This will minimize the number of recursions necessary, and in
    combination with caching values, will calculate practically any integer
    partition without the risk of a stack overflow.

    I can't help but think this is still grossly inefficient compared to what's
    possible.  It seems that using this algorithm, calculating any integer
    partition ends up necessitating calculating the integer partitions of
    every integer smaller than the original argument.
    '''
    debugPrint( 'partition', int( n ) )

    if real_int( n ) < 0:
        raise ValueError( 'non-negative argument expected' )
    elif n in ( 0, 1 ):
        return 1

    sign = 1
    i = 1
    k = 1

    estimate = log10( fdiv( power( e, fmul( pi, sqrt( fdiv( fmul( 2, n ), 3 ) ) ) ),
                            fprod( [ 4, n, sqrt( 3 ) ] ) ) )
    if mp.dps < estimate + 5:
        mp.dps = estimate + 5

    partitionList = [ ]
    signList = [ ]

    while n - k >= 0:
        partitionList.append( ( fsub( n, k ), sign ) )
        i += 1

        if i % 2:
            sign *= -1

        k = getNthGeneralizedPolygonalNumber( i, 5 )

    partitionList = partitionList[ : : -1 ]

    total = 0

    for partition, sign in partitionList:
        total = fadd( total, fmul( sign, getPartitionNumber( partition ) ) )

    return total
Example #32
0
def isKMorphic(n, k):
    '''
    Returns true if n to the k power ends with n.

    This code won't work correctly for integral powers of 10, but they can
    never be morphic anyway, except for 1, which I handle specially.
    '''
    if n == 1:
        return 1

    modulo = power(10, ceil(log10(n)))
    powmod = getPowMod(n, k, modulo)

    return 1 if (n == powmod) else 0
Example #33
0
def evaluate(algorithm: str, accuracy: int) -> mpmath.mpf:
    """Retrun Logarithm of the error between calculated pi and actural one.

    Args:
        algorithm (str): algorithm by which pi is calcurated
        accuracy (int): accuracy of calculated pi

    Returns:
        mpmath.mpf: logarithms or error of calculated pi and actual one
    """
    actual_pi: mpmath.mpf = calc('actual', ACTUAL_PI_DIGIT)
    compared_pi: mpmath.mpf = calc(algorithm, accuracy)
    subtraction: mpmath.mpf = mpmath.fsub(actual_pi, compared_pi)
    mpmath.mp.dps = ERROR_ACCRACY
    return -mpmath.log10(subtraction)
Example #34
0
def getPartitionNumber(n):
    '''
    This version is, um, less recursive than the original, which I've kept.
    The strategy is to create a list of the smaller partition numbers we need
    to calculate and then start calling them recursively, starting with the
    smallest.  This will minimize the number of recursions necessary, and in
    combination with caching values, will calculate practically any integer
    partition without the risk of a stack overflow.

    I can't help but think this is still grossly inefficient compared to what's
    possible.  It seems that using this algorithm, calculating any integer
    partition ends up necessitating calculating the integer partitions of
    every integer smaller than the original argument.
    '''
    debugPrint('partition', int(n))

    if n in (0, 1):
        return 1

    sign = 1
    i = 1
    k = 1

    estimate = log10(
        fdiv(power(e, fmul(pi, sqrt(fdiv(fmul(2, n), 3)))),
             fprod([4, n, sqrt(3)])))
    if mp.dps < estimate + 5:
        mp.dps = estimate + 5

    partitionList = []

    while n - k >= 0:
        partitionList.append((fsub(n, k), sign))
        i += 1

        if i % 2:
            sign *= -1

        k = getNthGeneralizedPolygonalNumber(i, 5)

    partitionList = partitionList[::-1]

    total = 0

    for partition, sign in partitionList:
        total = fadd(total, fmul(sign, getPartitionNumber(partition)))

    return total
Example #35
0
def assert_equal(vardict_1, vardict_2, suppress_message=False):
    """ Assert SymPy Expression Equality

        >>> from sympy import sin, cos
        >>> from sympy.abc import x

        >>> assert_equal(sin(2*x), 2*sin(x)*cos(x))
        Assertion Passed!
        >>> assert_equal(cos(2*x), cos(x)**2 - sin(x)**2)
        Assertion Passed!

        >>> assert_equal(cos(2*x), 1 - 2*sin(x)**2)
        Assertion Passed!
        >>> assert_equal(cos(2*x), 1 + 2*sin(x)**2)
        Traceback (most recent call last):
        ...
        AssertionError

        >>> vardict_1 = {'A': sin(2*x), 'B': cos(2*x)}
        >>> vardict_2 = {'A': 2*sin(x)*cos(x), 'B': cos(x)**2 - sin(x)**2}
        >>> assert_equal(vardict_1, vardict_2)
        Assertion Passed!

        >>> assert_equal('(a^2 - b^2) - (a + b)*(a - b)', 0)
        Assertion Passed!
    """
    if not isinstance(vardict_1, dict):
        vardict_1 = {'': vardict_1}
    if not isinstance(vardict_2, dict):
        vardict_2 = {'': vardict_2}
    for var_1, var_2 in zip(vardict_1, vardict_2):
        if not isinstance(vardict_1[var_1], sp.Basic):
            vardict_1[var_1] = sp.sympify(vardict_1[var_1])
        if not isinstance(vardict_2[var_2], sp.Basic):
            vardict_2[var_2] = sp.sympify(vardict_2[var_2])
    # update each vardict with mapping: variable -> (pseudo) unique number
    vardict_1, vardict_2 = update_vardict(vardict_1), update_vardict(vardict_2)
    # assert whether SDA >= (2/3) * precision, implying expression equality
    for var_1, var_2 in zip(vardict_1, vardict_2):
        n_1, n_2 = vardict_1[var_1], vardict_2[var_2]
        if n_1 == n_2: continue
        E_rel = 2 * fabs(n_1 - n_2)/(fabs(n_1) + fabs(n_2))
        assert -log10(E_rel) + 1 >= (2.0/3) * precision
    if not suppress_message:
        print('Assertion Passed!')
Example #36
0
def getDecimalDigitList(n, k):
    result = []

    setAccuracy(k)

    digits = floor(log10(n))

    if digits < 0:
        for _ in arange(fsub(fabs(digits), 1)):
            result.append(0)

        k = fsub(k, fsub(fabs(digits), 1))

    value = fmul(n, power(10, fsub(k, fadd(digits, 1))))

    for c in getMPFIntegerAsString(floor(value)):
        result.append(int(c))

    return result
Example #37
0
    def apply_2(self, n, evaluation):
        'MantissaExponent[n_]'
        n_sympy = n.to_sympy()
        expr = Expression('MantissaExponent', n)

        if isinstance(n.to_python(), complex):
            evaluation.message('MantissaExponent', 'realx', n)
            return expr
        # Handle Input with special cases such as PI and E
        if n_sympy.is_constant():
            temp_n = Expression('N', n).evaluate(evaluation)
            py_n = temp_n.to_python()
        else:
            return expr

        base_exp = int(mpmath.log10(py_n))
        exp = (base_exp + 1) if base_exp >= 0 else base_exp

        return Expression('List', Expression('Divide', n, (10**exp)), exp)
Example #38
0
    def apply_2(self, n, evaluation):
        "MantissaExponent[n_]"
        n_sympy = n.to_sympy()
        expr = Expression("MantissaExponent", n)

        if isinstance(n.to_python(), complex):
            evaluation.message("MantissaExponent", "realx", n)
            return expr
        # Handle Input with special cases such as PI and E
        if n_sympy.is_constant():
            temp_n = apply_N(n, evaluation)
            py_n = temp_n.to_python()
        else:
            return expr

        base_exp = int(mpmath.log10(py_n))
        exp = (base_exp + 1) if base_exp >= 0 else base_exp

        return Expression("List", Expression("Divide", n, (10**exp)), exp)
Example #39
0
def getLog10( n ):
    return log10( n )
Example #40
0
def compareResults( result1, result2 ):
    '''Compares two RPN expressions to make sure they produce the same result.
    Does nothing if the results compare successfully, otherwise raises an
    exception.'''

    if isinstance( result1, RPNGenerator ):
        return compareResults( list( result1.getGenerator( ) ), result2 )

    if isinstance( result2, RPNGenerator ):
        return compareResults( result1, list( result2.getGenerator( ) ) )

    if isinstance( result1, list ) != isinstance( result2, list ):
        print( '**** error in results comparison' )
        print( '    result 1: ', result1 )
        print( '    result 2: ', result2 )
        raise ValueError( 'one result is a list, the other isn\'t' )

    if isinstance( result1, str ) != isinstance( result2, str ):
        print( '**** error in results comparison' )
        print( '    result 1: ', result1 )
        print( '    result 2: ', result2 )
        raise ValueError( 'one result is a string, the other isn\'t' )

    if isinstance( result1, str ) and isinstance( result2, str ):
        if result1 != result2:
            print( '**** error in results comparison' )
            print( type( result1 ), type( result2 ) )
            print( result1, result2, 'are not equal' )
            raise ValueError( 'unit test failed' )
        else:
            return

    if isinstance( result1, RPNMeasurement ) and isinstance( result2, RPNMeasurement ):
        if result1 != result2:
            print( '**** error in results comparison' )
            print( type( result1 ), type( result2 ) )

            with workdps( 50 ):
                print( result1.value, result1.units, result2.value, result2.units, 'are not equal' )

            raise ValueError( 'unit test failed' )
        else:
            return True

    if isinstance( result1, list ) and isinstance( result2, list ):
        if len( result1 ) != len( result2 ):
            raise ValueError( 'lists are not of equal length:', len( result1 ), len( result2 ) )

        for i in range( 0, len( result1 ) ):
            if isinf( result1[ i ] ):
                if isinf( result2[ i ] ):
                    return True
                else:
                    print( '**** error in results comparison' )
                    print( type( result1[ i ] ), type( result2[ i ] ) )
                    print( result1[ i ], result2[ i ], 'are not equal' )

                    raise ValueError( 'unit test failed' )

            if not compareValues( result1[ i ], result2[ i ] ):
                digits = max( log10( result1[ i ] ), log10( result2[ i ] ) ) + 5

                mp.dps = digits

                print( '**** error in results comparison' )
                print( type( result1[ i ] ), type( result2[ i ] ) )
                print( result1[ i ], result2[ i ], 'are not equal' )
                print( 'difference', fsub( result1[ i ], result2[ i ] ) )
                print( 'difference found at index', i )

                raise ValueError( 'unit test failed' )
    else:
        if not compareValues( result1, result2 ):
            print( '**** error in results comparison' )
            print( '    result 1: ', result1 )
            print( '    result 2: ', result2 )

            raise ValueError( 'unit test failed' )
Example #41
0
def getMPFIntegerAsString( n ):
    if n == 0:
        return '0'
    else:
        return nstr( nint( n ), int( floor( log10( n ) + 10  ) ) )[ : -2 ]
Example #42
0
    ( 'reaumur', 'delisle' )                    : lambda re: fmul( fsub( 80, re ), fdiv( 15, 8 ) ),
    ( 'reaumur', 'fahrenheit' )                 : lambda re: fadd( fmul( re, fdiv( 9, 4 ) ), 32 ),
    ( 'reaumur', 'kelvin' )                     : lambda re: fadd( fmul( re, fdiv( 5, 4 ) ), mpf( '273.15' ) ),
    ( 'reaumur', 'rankine' )                    : lambda re: fadd( fmul( re, fdiv( 9, 4 ) ), mpf( '491.67' ) ),
    ( 'reaumur', 'romer' )                      : lambda re: fadd( fmul( re, fdiv( 21, 32 ) ), mpf( 7.5 ) ),

    ( 'romer', 'celsius' )                      : lambda ro: fmul( fsub( ro, mpf( '7.5' ) ), fdiv( 40, 21 ) ),
    ( 'romer', 'degree_newton' )                : lambda ro: fmul( fsub( ro, mpf( '7.5' ) ), fdiv( 22, 35 ) ),
    ( 'romer', 'delisle' )                      : lambda ro: fmul( fsub( 60, ro ), fdiv( 20, 7 ) ),
    ( 'romer', 'fahrenheit' )                   : lambda ro: fadd( fmul( fsub( ro, mpf( '7.5' ) ), fdiv( 24, 7 ) ), 32 ),
    ( 'romer', 'kelvin' )                       : lambda ro: fadd( fmul( fsub( ro, mpf( '7.5' ) ), fdiv( 40, 21 ) ), mpf( '273.15' ) ),
    ( 'romer', 'rankine' )                      : lambda ro: fadd( fmul( fsub( ro, mpf( '7.5' ) ), fdiv( 24, 7 ) ), mpf( '491.67' ) ),
    ( 'romer', 'reaumur' )                      : lambda ro: fmul( fsub( ro, mpf( '7.5' ) ), fdiv( 32, 21 ) ),

    ( 'decibel-volt', 'volt' )                  : lambda dBV: power( 10, fdiv( dBV, 10 ) ),
    ( 'volt', 'decibel-volt' )                  : lambda V: fmul( log10( V ), 10 ),

    ( 'decibel-watt', 'watt' )                  : lambda dBW: power( 10, fdiv( dBW, 10 ) ),
    ( 'watt', 'decibel-watt' )                  : lambda W: fmul( log10( W ), 10 ),

    ( 'decibel-milliwatt', 'watt' )             : lambda dBm: power( 10, fdiv( fsub( dBm, 30 ), 10 ) ),
    ( 'watt', 'decibel-milliwatt' )             : lambda W: fmul( log10( fmul( W, 1000 ) ), 10 ),

    ( 'second', 'hertz' )                       : lambda second: fdiv( 1, second ),

    ( 'hertz', 'second' )                       : lambda hertz: fdiv( 1, hertz ),

    ( 'ohm', 'siemens' )                        : lambda ohm: fdiv( 1, ohm ),

    ( 'siemens', 'ohm' )                        : lambda siemens: fdiv( 1, siemens ),
}
Example #43
0
def describeInteger( n ):
    if n < 1:
        raise ValueError( "'describe' requires a positive integer argument" )

    indent = ' ' * 4

    print( )
    print( real_int( n ), 'is:' )

    if isOdd( n ):
        print( indent + 'odd' )
    elif isEven( n ):
        print( indent + 'even' )

    if isPrimeNumber( n ):
        isPrime = True
        print( indent + 'prime' )
    elif n > 3:
        isPrime = False
        print( indent + 'composite' )
    else:
        isPrime = False

    if isKthPower( n, 2 ):
        print( indent + 'the ' + getShortOrdinalName( sqrt( n ) ) + ' square number' )

    if isKthPower( n, 3 ):
        print( indent + 'the ' + getShortOrdinalName( cbrt( n ) ) + ' cube number' )

    for i in arange( 4, fadd( ceil( log( fabs( n ), 2 ) ), 1 ) ):
        if isKthPower( n, i ):
            print( indent + 'the ' + getShortOrdinalName( root( n, i ) ) + ' ' + \
                   getNumberName( i, True ) + ' power'  )

    # triangular
    guess = findPolygonalNumber( n, 3 )

    if getNthPolygonalNumber( guess, 3 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' triangular number' )

    # pentagonal
    guess = findPolygonalNumber( n, 5 )

    if getNthPolygonalNumber( guess, 5 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' pentagonal number' )

    # hexagonal
    guess = findPolygonalNumber( n, 6 )

    if getNthPolygonalNumber( guess, 6 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' hexagonal number' )

    # heptagonal
    guess = findPolygonalNumber( n, 7 )

    if getNthPolygonalNumber( guess, 7 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' heptagonal number' )

    # octagonal
    guess = findPolygonalNumber( n, 8 )

    if getNthPolygonalNumber( guess, 8 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' octagonal number' )

    # nonagonal
    guess = findPolygonalNumber( n, 9 )

    if getNthPolygonalNumber( guess, 9 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' nonagonal number' )

    # decagonal
    guess = findPolygonalNumber( n, 10 )

    if getNthPolygonalNumber( guess, 10 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' decagonal number' )

    #if n > 1:
    #    for i in range( 11, 101 ):
    #        if getNthPolygonalNumber( findPolygonalNumber( n, i ), i ) == n:
    #            print( indent + str( i ) + '-gonal' )

    # centered triangular
    guess = findCenteredPolygonalNumber( n, 3 )

    if getNthCenteredPolygonalNumber( guess, 3 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' centered triangular' )

    # centered square
    guess = findCenteredPolygonalNumber( n, 4 )

    if getNthCenteredPolygonalNumber( guess, 4 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' centered square number' )

    # centered pentagonal
    guess = findCenteredPolygonalNumber( n, 5 )

    if getNthCenteredPolygonalNumber( guess, 5 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' centered pentagonal number' )

    # centered hexagonal
    guess = findCenteredPolygonalNumber( n, 6 )

    if getNthCenteredPolygonalNumber( guess, 6 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' centered hexagonal number' )

    # centered heptagonal
    guess = findCenteredPolygonalNumber( n, 7 )

    if getNthCenteredPolygonalNumber( guess, 7 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' centered heptagonal number' )

    # centered octagonal
    guess = findCenteredPolygonalNumber( n, 8 )

    if getNthCenteredPolygonalNumber( guess, 8 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' centered octagonal number' )

    # centered nonagonal
    guess = findCenteredPolygonalNumber( n, 9 )

    if getNthCenteredPolygonalNumber( guess, 9 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' centered nonagonal number' )

    # centered decagonal
    guess - findCenteredPolygonalNumber( n, 10 )

    if getNthCenteredPolygonalNumber( guess, 10 ) == n:
        print( indent + 'the ' + getShortOrdinalName( guess ) + ' centered decagonal number' )

    # pandigital
    if isPandigital( n ):
        print( indent + 'pandigital' )

    #for i in range( 4, 21 ):
    #    if isBaseKPandigital( n, i ):
    #        print( indent + 'base ' + str( i ) + ' pandigital' )

    # Fibonacci
    result = findInput( n, fib, lambda n: fmul( log10( n ), 5 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Fibonacci number' )

    # Tribonacci
    result = findInput( n, lambda n : getNthKFibonacciNumber( n, 3 ), lambda n: fmul( log10( n ), 5 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Tribonacci number' )

    # Tetranacci
    result = findInput( n, lambda n : getNthKFibonacciNumber( n, 4 ), lambda n: fmul( log10( n ), 5 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Tetranacci number' )

    # Pentanacci
    result = findInput( n, lambda n : getNthKFibonacciNumber( n, 5 ), lambda n: fmul( log10( n ), 5 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Pentanacci number' )

    # Hexanacci
    result = findInput( n, lambda n : getNthKFibonacciNumber( n, 6 ), lambda n: fmul( log10( n ), 5 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Hexanacci number' )

    # Heptanacci
    result = findInput( n, lambda n : getNthKFibonacciNumber( n, 7 ), lambda n: fmul( log10( n ), 5 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Heptanacci number' )

    # Octanacci
    result = findInput( n, lambda n : getNthKFibonacciNumber( n, 8 ), lambda n: fmul( log10( n ), 5 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Octanacci number' )

    # Lucas numbers
    result = findInput( n, getNthLucasNumber, lambda n: fmul( log10( n ), 5 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Lucas number' )

    # base-k repunits
    if n > 1:
        for i in range( 2, 21 ):
            result = findInput( n, lambda x: getNthBaseKRepunit( x, i ), lambda n: log( n, i ) )

            if result[ 0 ]:
                print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' base-' + str( i ) + ' repunit' )

    # Jacobsthal numbers
    result = findInput( n, getNthJacobsthalNumber, lambda n: fmul( log( n ), 1.6 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Jacobsthal number' )

    # Padovan numbers
    result = findInput( n, getNthPadovanNumber, lambda n: fmul( log10( n ), 9 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Padovan number' )

    # Fibonorial numbers
    result = findInput( n, getNthFibonorial, lambda n: sqrt( fmul( log( n ), 10 ) ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Fibonorial number' )

    # Mersenne primes
    result = findInput( n, getNthMersennePrime, lambda n: fadd( fmul( log( log( sqrt( n ) ) ), 2.7 ), 3 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Mersenne prime' )

    ## perfect number
    result = findInput( n, getNthPerfectNumber, lambda n: fmul( log( log( n ) ), 2.6 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' perfect number' )

    # Mersenne exponent
    result = findInput( n, getNthMersenneExponent, lambda n: fmul( log( n ), 2.7 ), max=50 )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Mersenne exponent' )

    if not isPrime and n != 1 and n <= largestNumberToFactor:
        # deficient
        if isDeficient( n ):
            print( indent + 'deficient' )

        # abundant
        if isAbundant( n ):
            print( indent + 'abundant' )

        # k_hyperperfect
        for i in sorted( list( set( sorted( downloadOEISSequence( 34898 )[ : 500 ] ) ) ) )[ 1 : ]:
            if i > n:
                break

            if isKHyperperfect( n, i ):
                print( indent + str( i ) + '-hyperperfect' )
                break

        # smooth
        for i in getPrimes( 2, 50 ):
            if isSmooth( n, i ):
                print( indent + str( i ) + '-smooth' )
                break

        # rough
        previousPrime = 2

        for i in getPrimes( 2, 50 ):
            if not isRough( n, i ):
                print( indent + str( previousPrime ) + '-rough' )
                break

            previousPrime = i

        # is_semiprime
        if isSemiprime( n ):
            print( indent + 'semiprime' )

        # is_sphenic
        elif isSphenic( n ):
            print( indent + 'sphenic' )
        elif isSquareFree( n ):
            print( indent + 'square-free' )

        # powerful
        if isPowerful( n ):
            print( indent + 'powerful' )

    # factorial
    result = findInput( n, getNthFactorial, lambda n: power( log10( n ), 0.92 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' factorial number' )

    # alternating factorial
    result = findInput( n, getNthAlternatingFactorial, lambda n: fmul( sqrt( log( n ) ), 0.72 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' alternating factorial number' )

    # double factorial
    if n == 1:
        result = ( True, 1 )
    else:
        result = findInput( n, getNthDoubleFactorial, lambda n: fdiv( power( log( log( n ) ), 4 ), 7 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' double factorial number' )

    # hyperfactorial
    result = findInput( n, getNthHyperfactorial, lambda n: fmul( sqrt( log( n ) ), 0.8 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' hyperfactorial number' )

    # subfactorial
    result = findInput( n, getNthSubfactorial, lambda n: fmul( log10( n ), 1.1 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' subfactorial number' )

    # superfactorial
    if n == 1:
        result = ( True, 1 )
    else:
        result = findInput( n, getNthSuperfactorial, lambda n: fadd( sqrt( log( n ) ), 1 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' superfactorial number' )

    # pernicious
    if isPernicious( n ):
        print( indent + 'pernicious' )

    # pronic
    if isPronic( n ):
        print( indent + 'pronic' )


    # Achilles
    if isAchillesNumber( n ):
        print( indent + 'an Achilles number' )

    # antiharmonic
    if isAntiharmonic( n ):
        print( indent + 'antiharmonic' )

    # unusual
    if isUnusual( n ):
        print( indent + 'unusual' )

    # hyperperfect
    for i in range( 2, 21 ):
        if isKHyperperfect( n, i ):
            print( indent + str( i ) + '-hyperperfect' )

    # Ruth-Aaron
    if isRuthAaronNumber( n ):
        print( indent + 'a Ruth-Aaron number' )

    # Smith numbers
    if isSmithNumber( n ):
        print( indent + 'a Smith number' )

    # base-k Smith numbers
    for i in range( 2, 10 ):
        if isBaseKSmithNumber( n, i ):
            print( indent + 'a base-' + str( i ) + ' Smith number' )

    # order-k Smith numbers
    for i in range( 2, 11 ):
        if isOrderKSmithNumber( n, i ):
            print( indent + 'an order-' + str( i ) + ' Smith number' )

    # polydivisible
    if isPolydivisible( n ):
        print( indent + 'polydivisible' )

    # Carol numbers
    result = findInput( n, getNthCarolNumber, lambda n: fmul( log10( n ), fdiv( 5, 3 ) ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Carol number' )

    # Kynea numbers
    result = findInput( n, getNthKyneaNumber, lambda n: fmul( log10( n ), fdiv( 5, 3 ) ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Kynea number' )

    # Leonardo numbers
    result = findInput( n, getNthLeonardoNumber, lambda n: fsub( log( n, phi ), fdiv( 1, phi ) ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Leonardo number' )

    # Riesel numbers
    result = findInput( n, getNthRieselNumber, lambda n: fmul( log( n ), 1.25 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Riesel number' )

    # Thabit numbers
    result = findInput( n, getNthThabitNumber, lambda n: fmul( log10( n ), 3.25 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Thabit number' )

    # Carmmichael
    if isCarmichaelNumber( n ):
        print( indent + 'a Carmichael number' )

    # narcissistic
    if isNarcissistic( n ):
        print( indent + 'narcissistic' )

    # PDI
    if isPerfectDigitalInvariant( n ):
        print( indent + 'a perfect digital invariant' )

    # PDDI
    if isPerfectDigitToDigitInvariant( n, 10 ):
        print( indent + 'a perfect digit-to-digit invariant in base 10' )

    # Kaprekar
    if isKaprekar( n ):
        print( indent + 'a Kaprekar number' )

    # automorphic
    if isAutomorphic( n ):
        print( indent + 'automorphic' )

    # trimorphic
    if isTrimorphic( n ):
        print( indent + 'trimorphic' )

    # k-morphic
    for i in range( 4, 11 ):
        if isKMorphic( n, i ):
            print( indent + str( i ) + '-morphic' )

    # bouncy
    if isBouncy( n ):
        print( indent + 'bouncy' )

    # step number
    if isStepNumber( n ):
        print( indent + 'a step number' )

    # Apery numbers
    result = findInput( n, getNthAperyNumber, lambda n: fadd( fdiv( log( n ), 1.5 ), 1 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Apery number' )

    # Delannoy numbers
    result = findInput( n, getNthDelannoyNumber, lambda n: fmul( log10( n ), 1.35 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Delannoy number' )

    # Schroeder numbers
    result = findInput( n, getNthSchroederNumber, lambda n: fmul( log10( n ), 1.6 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Schroeder number' )

    # Schroeder-Hipparchus numbers
    result = findInput( n, getNthSchroederHipparchusNumber, lambda n: fdiv( log10( n ), 1.5 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Schroeder-Hipparchus number' )

    # Motzkin numbers
    result = findInput( n, getNthMotzkinNumber, lambda n: log( n ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Motzkin number' )

    # Pell numbers
    result = findInput( n, getNthPellNumber, lambda n: fmul( log( n ), 1.2 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Pell number' )

    # Sylvester numbers
    if n > 1:
        result = findInput( n, getNthSylvesterNumber, lambda n: sqrt( sqrt( log( n ) ) ) )

        if result[ 0 ]:
            print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' Sylvester number' )

    # partition numbers
    result = findInput( n, getPartitionNumber, lambda n: power( log( n ), 1.56 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' partition number' )

    # menage numbers
    result = findInput( n, getNthMenageNumber, lambda n: fdiv( log10( n ), 1.2 ) )

    if result[ 0 ]:
        print( indent + 'the ' + getShortOrdinalName( result[ 1 ] ) + ' menage number' )

    print( )
    print( int( n ), 'has:' )

    # number of digits
    digits = log10( n )

    if isInteger( digits ):
        digits += 1
    else:
        digits = ceil( digits )

    print( indent + str( int( digits ) ) + ' digit' + ( 's' if digits > 1 else '' ) )

    # digit sum
    print( indent + 'a digit sum of ' + str( int( sumDigits( n ) ) ) )

    # digit product
    digitProduct = multiplyDigits( n )

    print( indent + 'a digit product of ' + str( int( digitProduct ) ) )

    # non-zero digit product
    if digitProduct == 0:
        print( indent + 'a non-zero digit product of ' + str( int( multiplyNonzeroDigits( n ) ) ) )

    if not isPrime and n != 1 and n <= largestNumberToFactor:
        # factors
        factors = getFactors( n )
        factorCount = len( factors )
        print( indent + str( factorCount ) + ' prime factor' + ( 's' if factorCount > 1 else '' ) + \
               ': ' + ', '.join( [ str( int( i ) ) for i in factors ] ) )

        # number of divisors
        divisorCount = int( getDivisorCount( n ) )
        print( indent + str( divisorCount ) + ' divisor' + ( 's' if divisorCount > 1 else '' ) )

    if n <= largestNumberToFactor:
        print( indent + 'a sum of divisors of ' + str( int( getSigma( n ) ) ) )
        print( indent + 'a Stern value of ' + str( int( getNthStern( n ) ) ) )
        calkin_wilf = getNthCalkinWilf( n )
        print( indent + 'a Calkin-Wilf value of ' + str( int( calkin_wilf[ 0 ] ) ) + '/' + str( int( calkin_wilf[ 1 ] ) ) )
        print( indent + 'a Mobius value of ' + str( int( getMobius( n ) ) ) )
        print( indent + 'a radical of ' + str( int( getRadical( n ) ) ) )
        print( indent + 'a Euler phi value of ' + str( int( getEulerPhi( n ) ) ) )

    print( indent + 'a digital root of ' + str( int( getDigitalRoot( n ) ) ) )

    if hasUniqueDigits( n ):
        print( indent + 'unique digits' )

    print( indent + 'a multiplicative persistence of ' + str( int( getPersistence( n ) ) ) )
    print( indent + 'an Erdos persistence of ' + str( int( getErdosPersistence( n ) ) ) )

    if n > 9 and isIncreasing( n ):
        if not isDecreasing( n ):
            print( indent + 'increasing digits' )
    elif n > 9 and isDecreasing( n ):
        print( indent + 'decreasing digits' )

    print( )

    return n
Example #44
0
def LuminosityFunction(luminosityParameter,luminosity):
	return np.log10(luminosityParameter[0])+float(mpmath.log10(mpmath.gammainc(luminosityParameter[2]+1,luminosity/luminosityParameter[1])))
Example #45
0
def rootfinding(luminosity,luminosityParameter,nold):
	return np.log10(luminosityParameter[0][0])+float(mpmath.log10(mpmath.gammainc(luminosityParameter[2][0]+1,luminosity/luminosityParameter[1][0])))-float(nold)