def check_threshold(self, KL_pq, KL_qp, current_time):
     tol = 1e-10
     self.KL_pq = np.append(self.KL_pq, KL_pq)
     self.KL_qp = np.append(self.KL_qp, KL_qp)
     u_pq = (KL_pq - 1) / (np.exp(1))
     if u_pq > -1 / mp.e + tol:
         Lambda_upper = float(mp.lambertw(u_pq) + 1)
     else:
         Lambda_upper = 0
     u_qp = (KL_qp - 1) / (np.exp(1))
     if u_qp > -1 / mp.e + tol:
         Lambda_lower = float(mp.lambertw(u_qp) + 1)
     else:
         Lambda_lower = 0
     self.R_upper = np.append(self.R_upper, (np.exp(Lambda_upper) - 1))
     self.R_lower = np.append(self.R_lower, (np.exp(Lambda_lower) - 1))
     self.R = np.append(self.R, self.R_upper[-1] + self.R_lower[-1])
     if self.validate_size <= current_time:
         error_ratio = self.R[-1] / self.R[:self.validate_size + 1].min()
         if self.validate_size == current_time:
             error_ratio = 1
         self.error_ratio = np.append(self.error_ratio, error_ratio)
         if self.error_ratio[-1] <= self.threshold and not self.stop_flags:
             self.stop_timings = current_time
             print("{} : {}".format(self.criterion_name, current_time))
             self.stop_flags = True
     else:
         self.error_ratio = np.append(self.error_ratio, 1)
Exemplo n.º 2
0
def expit(b,t,z,prec=100,n=10,r=None):
  N = n
  oprec = (b+t).prec()

  if b == 1:
    return ComplexField(oprec)(1)

  C = ComplexField(prec)
  FC = FormalPowerSeriesRing(C)
  lnb = log(C(b))
  mpmath.mp.prec = prec
  lna = mpc2C(-mpmath.lambertw(-lnb))
  if abs(lna)>1:
    print 'b:',b,'abs(lna):',abs(lna)
    return None
  a = exp(lna)
  # print 'a',a,'|lna|',abs(lna)
  if r == None:
    r = 1 - abs(lna)

  zn = z
  n=0
  while abs(log(zn)-lna) > r:
    zn = b**zn
    n+=1
  #  print 'zn',n,zn
  # print zn
  h = FC.Dec_exp.rmul(lna)
  # w = ComplexField(oprec)(a+h.it(t).polynomial(N)(lnb*(1-a))/lnb)
  # print 'w',w
  wn = ComplexField(oprec)(a+h.it(t).polynomial(N)(lnb*(zn-a))/lnb)
  for k in range(1,n+1):
    wn = log(wn)/lnb
    # print 'wn',k,wn
  return wn
Exemplo n.º 3
0
def getSuperRootsOperator(n, k):
    '''Returns all the super-roots of n, not just the nice, positive, real one.'''
    k = fsub(k, 1)
    factors = [fmul(i, root(k, k)) for i in unitroots(int(k))]
    base = root(fdiv(log(n), lambertw(fmul(k, log(n)))), k)

    return [fmul(i, base) for i in factors]
Exemplo n.º 4
0
    def solve_MS_approx_for_phi(self, valence):
        """Calculate the space-charge potential, :math:`\phi_0`, from the grain-boundary resistivity ratio, within the Mott-Schottky approximation.
        Within the Mott-Schottky approximation the grain boundary resistivity is related to the space-charge potential (the electrostatic potential at the grain boundary core, compared to the bulk value) according to
        
        .. math:: r_\mathrm{gb} = \frac{\rho_{i,\mathrm{gb}}}{\rho_{i,\infty}} = \frac{\exp(z_i\phi_0 / V_\mathrm{th})}{2z_i\phi_0/V_\mathrm{th}}
       
        where

        .. math:: V_\mathrm{th} = \frac{k_\mathrm{B}T}{q}.

        (See e.g. `S. Kim, Phys. Chem. Chem. Phys. 18, 19787 (2016).`_)

        .. _S. Kim, Phys. Chem. Chem. Phys. 18, 19787 (2016).: https://dx.doi.org/10.1039/c6cp02177h

        This allows a Mott-Schottky space-charge potential, :math:`\phi_{0,\mathrm{MS}}`, to be calculated using the `LambertW`_ function:

        .. math:: \phi_{0,\mathrm{MS}} = -\mathrm{LambertW}\left(\frac{1}{2 r_\mathrm{gb}}\right)\frac{V_\mathrm{th}}{z_i}.
        .. _LambertW: https://en.wikipedia.org/wiki/Lambert_W_function

        The output is stored as a Calculation attribute. Calculation.ms_phi (float): :math:`\phi_{0,\mathrm{MS}}`. The space charge potential calculated from Mott-Schottky model.


        Args:
            valence( float ): Charge of the mobile defect species. 
   
        Raises:
            ValueError: If the calculated resistivity ratio is less than 1.36, the LambertW function returns a complex, non-physical value.

        """
        if self.perpendicular_resistivity_ratio < 1.36:
            raise ValueError(
                "Resistivity ratio < 1.36. Solution not on a real branch.")
        self.ms_phi = (-mpmath.lambertw(
            -1 / (2 * self.perpendicular_resistivity_ratio), k=-1)) * (
                (boltzmann_eV * self.temp) / valence)
Exemplo n.º 5
0
 def updateCurrent(self):
   Rs = self.Rs
   Rsh = self.Rsh
   n = self.n
   I0 = self.I0
   Iph = self.Iph
   Vth = self.Vth
   V = self.V
   I = (Rs*(I0*Rsh + Iph*Rsh - V) - Vth*n*(Rs + Rsh)*mpmath.lambertw(I0*Rs*Rsh*mpmath.exp((Rs*(I0*Rsh + Iph*Rsh - V)/(Rs + Rsh) + V)/(Vth*n))/(Vth*n*(Rs + Rsh))))/(Rs*(Rs + Rsh))
   self.I = float(-1*numpy.real_if_close(numpy.complex(I)))
Exemplo n.º 6
0
 def openCircuitEvent(self):
   self.I = 0
   Rs = self.Rs
   Rsh = self.Rsh
   n = self.n
   I0 = self.I0
   Iph = self.Iph
   Vth = self.Vth
   Voc = I0*Rsh + Iph*Rsh - Vth*n*mpmath.lambertw(I0*Rsh*mpmath.exp(Rsh*(I0 + Iph)/(Vth*n))/(Vth*n))
   self.V = float(numpy.real_if_close(numpy.complex(Voc)))
Exemplo n.º 7
0
def optimal_transmission_power_device_2(beta_t, beta_e, mu, sigma, P, h, k, N):
    A3 = 1 + beta_t / (beta_e * P)
    B3 = lambda i: (h[i] * beta_t) / (beta_e * sigma**2) - 1
    A4 = 1 + mu / (beta_e * P)
    B4 = lambda i: (h[i] * mu) / (beta_e * sigma**2) - 1
    cond = lambda i: h[i] < (sigma**2 / P) * (A4 / -(mpmath.lambertw(
        -A4 * math.exp(-A4))) - 1)
    l1 = [
        P if cond(i) else
        (sigma**2 / h[i]) * (B4(i) / (mpmath.lambertw(B4(i) / math.e)) - 1)
        for i in range(k + 1)
    ]
    cond = lambda i: h[i] < (sigma**2 / P) * (A3 / -(mpmath.lambertw(
        -A3 * math.exp(-A3))) - 1)
    l2 = [
        P if cond(i) else
        (sigma**2 / h[i]) * (B3(i) / (mpmath.lambertw(B3(i) / math.e)) - 1)
        for i in range(k + 1, N + 2)
    ]
    return l1 + l2
Exemplo n.º 8
0
def main():
    parser = argparse.ArgumentParser(description='Analyse Serial Diode')
    parser.add_argument('Vs', type=float, help='Voltage supply')
    parser.add_argument('R', type=float, help='Resistor value in Ohms')
    parser.add_argument(
        'Is',
        type=float,
        nargs='?',
        default=1e-12,
        help='Diode Saturation current in Amps (default = 1e-12)')
    parser.add_argument('N',
                        type=float,
                        nargs='?',
                        default=1,
                        help='Emission Coefficient (default = 1)')
    parser.add_argument('--Vt',
                        type=float,
                        default=0.026,
                        help='Thermal Voltage in Volts (default = 0.026)')
    parser.add_argument('-g',
                        '--graph',
                        action='store_true',
                        help='Draw a graph')
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help='Print debug')
    args = parser.parse_args()

    Vs = args.Vs
    R = args.R
    Is = args.Is
    N = args.N
    Vt = args.Vt
    nVt = N * Vt

    if args.verbose:
        logging.basicConfig(format='%(levelname)s|%(message)s',
                            level=logging.INFO)
    logging.info(f'Vs: {Vs}, R: {R}, Is: {Is}, N: {N}, Vt: {Vt}')

    x = fdiv(fmul(fmul(Is, R), fsub(exp(fdiv(Vs, nVt)), mpf(1))), nVt)
    w = lambertw(x)
    Id = fdiv(fmul(w, nVt), R)
    Vd = fmul(log(fadd(fdiv(Id, Is), mpf(1))), nVt)
    VR = fsub(Vs, Vd)
    IR = fdiv(VR, R)
    print("VR: {}, IR: {}".format(VR, IR))
    print("Vd: {}, Id: {}".format(Vd, Id))
    if args.graph:
        plot([
            lambda x: fsub(Vs, fmul(x, R)),
            lambda x: fmul(nVt, log(fadd(fdiv(x, Is), 1)))
        ], [0, fdiv(Vs, R)], [0, Vs])
Exemplo n.º 9
0
 def ThermionicEmissionCurrent(self, Va, phi_bn, debug=False):
     kT = to_numeric(k * self.T)
     q_n = to_numeric(q)
     A = self.Area
     Rs = self.Rs
     if self.Semiconductor.dop_type == 'n':
         Ar = self.Semiconductor.reference['A_R_coeff_n'] * constants['A_R']
     else:
         Ar = self.Semiconductor.reference['A_R_coeff_p'] * constants['A_R']
     Js = Ar * (self.T ** 2) * mp.exp(-q_n * phi_bn / kT)
     if debug: print 'Js, Is =', Js, A * Js
     J = -Js + kT / (q_n * A * Rs) * mp.lambertw((q_n * A * Rs * Js / kT) * mp.exp(q_n * (Va + A * Js * Rs) / kT))
     if debug: print 'J, I =', J, A * J
     Vd = Va - A * J * Rs
     return np.float(Vd), np.float(J)
Exemplo n.º 10
0
  def solve_MS_approx_for_phi(self, valence):
      """
      Using the calculated resistivity ratio, solves the Mott-Schottky model to calculate the space charge potential (analogous to experimental analysis).
      If the resistivity ratio calculated is less that 1.36, ValueError raised as solution to the Mott-Schottky model is not on a real branch.
      Args:
          valence( float ): Charge of species at site. 
 
      Returns:
          ms_phi( float ): Space charge potential calculated from Mott-Schottky model
      """
      if self.perpendicular_resistivity_ratio < 1.36:
          raise ValueError(
              "Resistivity ratio < 1.36. Solution not on a real branch.")
      self.ms_phi = (-mpmath.lambertw(
          -1 / (2 * self.perpendicular_resistivity_ratio), k=-1)) * (
              (boltzmann_eV * self.temp) / valence)
Exemplo n.º 11
0
def F(p_l, x_l):
    k0_l, xb_l, km_l = p_l[0], p_l[1], p_l[2]
    D_l = k0_l * sqrt(
        2 * pi) / (km_l**(1.5) * xb_l * exp(-0.5 * km_l * xb_l**2)
                   )  #Rozwiązanie równiania nr 3 w Mat Sup- Schulten.pdf
    b = D_l * (km_l + ks)
    out = []
    for i in range(len(x_l)):
        vel_l = x_l[i]
        a = (xb_l * D_l * (km_l + ks)**2 / (ks * vel_l) + 1)
        tau = (lambertw(-exp(-a)) +
               a) / b  #Rozwiązanie równania nr 4 w Supp Mat - Szulten
        out.append(
            -ks * 300 * kb *
            (xb_l - vel_l * quad(s, 0, tau, args=(vel_l, p_l), epsabs=1e-16)[0]
             ))  #Wzór nr 5 w Mat Sup- Schulten.pdf
    return array(out)
Exemplo n.º 12
0
def main():
    print(__doc__)
    with mpmath.workdps(50):
        p, q = lambertw_pade()
        p, q = p[::-1], q[::-1]
        print("p = {}".format(p))
        print("q = {}".format(q))

    x, y = np.linspace(-1.5, 1.5, 75), np.linspace(-1.5, 1.5, 75)
    x, y = np.meshgrid(x, y)
    z = x + 1j*y
    lambertw_std = []
    for z0 in z.flatten():
        lambertw_std.append(complex(mpmath.lambertw(z0)))
    lambertw_std = np.array(lambertw_std).reshape(x.shape)

    fig, axes = plt.subplots(nrows=3, ncols=1)
    # Compare Pade approximation to true result
    p = np.array([float(p0) for p0 in p])
    q = np.array([float(q0) for q0 in q])
    pade_approx = np.polyval(p, z)/np.polyval(q, z)
    pade_err = abs(pade_approx - lambertw_std)
    axes[0].pcolormesh(x, y, pade_err)
    # Compare two terms of asymptotic series to true result
    asy_approx = np.log(z) - np.log(np.log(z))
    asy_err = abs(asy_approx - lambertw_std)
    axes[1].pcolormesh(x, y, asy_err)
    # Compare two terms of the series around the branch point to the
    # true result
    p = np.sqrt(2*(np.exp(1)*z + 1))
    series_approx = -1 + p - p**2/3
    series_err = abs(series_approx - lambertw_std)
    im = axes[2].pcolormesh(x, y, series_err)

    fig.colorbar(im, ax=axes.ravel().tolist())
    plt.show()

    fig, ax = plt.subplots(nrows=1, ncols=1)
    pade_better = pade_err < asy_err
    im = ax.pcolormesh(x, y, pade_better)
    t = np.linspace(-0.3, 0.3)
    ax.plot(-2.5*abs(t) - 0.2, t, 'r')
    fig.colorbar(im, ax=ax)
    plt.show()
Exemplo n.º 13
0
def main():
    print(__doc__)
    with mpmath.workdps(50):
        p, q = lambertw_pade()
        p, q = p[::-1], q[::-1]
        print("p = {}".format(p))
        print("q = {}".format(q))

    x, y = np.linspace(-1.5, 1.5, 75), np.linspace(-1.5, 1.5, 75)
    x, y = np.meshgrid(x, y)
    z = x + 1j * y
    lambertw_std = []
    for z0 in z.flatten():
        lambertw_std.append(complex(mpmath.lambertw(z0)))
    lambertw_std = np.array(lambertw_std).reshape(x.shape)

    fig, axes = plt.subplots(nrows=3, ncols=1)
    # Compare Pade approximation to true result
    p = np.array([float(p0) for p0 in p])
    q = np.array([float(q0) for q0 in q])
    pade_approx = np.polyval(p, z) / np.polyval(q, z)
    pade_err = abs(pade_approx - lambertw_std)
    axes[0].pcolormesh(x, y, pade_err)
    # Compare two terms of asymptotic series to true result
    asy_approx = np.log(z) - np.log(np.log(z))
    asy_err = abs(asy_approx - lambertw_std)
    axes[1].pcolormesh(x, y, asy_err)
    # Compare two terms of the series around the branch point to the
    # true result
    p = np.sqrt(2 * (np.exp(1) * z + 1))
    series_approx = -1 + p - p**2 / 3
    series_err = abs(series_approx - lambertw_std)
    im = axes[2].pcolormesh(x, y, series_err)

    fig.colorbar(im, ax=axes.ravel().tolist())
    plt.show()

    fig, ax = plt.subplots(nrows=1, ncols=1)
    pade_better = pade_err < asy_err
    im = ax.pcolormesh(x, y, pade_better)
    t = np.linspace(-0.3, 0.3)
    ax.plot(-2.5 * abs(t) - 0.2, t, 'r')
    fig.colorbar(im, ax=ax)
    plt.show()
Exemplo n.º 14
0
def invcdf(p, a, b):
    """
    Inverse CDF of the Benktander II distribution.

    Variable names follow the convention used on wikipedia.
    """
    _validate_ab(a, b)
    if p < 0 or p > 1:
        return mpmath.nan
    with mpmath.extradps(5):
        p = mpmath.mpf(p)
        a = mpmath.mpf(a)
        b = mpmath.mpf(b)
        one = mpmath.mp.one
        if b == 1:
            return one - mpmath.log1p(-p) / a
        else:
            onemb = one - b
            c = a / onemb
            t = c * mpmath.exp(c) * mpmath.power(one - p, -b / onemb)
            return mpmath.power(mpmath.lambertw(t) / c, 1 / b)
Exemplo n.º 15
0
def main(argv):
    if len(argv) != 4:
        print "Analyse Serial Diode"
        print "Usage: asd <Vcc> <R> <Is> <nVt>"
    else:
        Vcc = mpf(argv[0])
        R = mpf(argv[1])
        Is = mpf(argv[2])
        nVt = mpf(argv[3])
        x = fdiv(fmul(fmul(Is, R), fsub(exp(fdiv(Vcc, nVt)), mpf(1))), nVt)
        w = lambertw(x)
        Id = fdiv(fmul(w, nVt), R)
        Vd = fmul(log(fadd(fdiv(Id, Is), mpf(1))), nVt)
        VR = fsub(Vcc, Vd)
        IR = fdiv(VR, R)
        print "VR: {}, IR: {}".format(VR, IR)
        print "Vd: {}, Id: {}".format(Vd, Id)
        plot([
            lambda x: fsub(Vcc, fmul(x, R)),
            lambda x: fmul(nVt, log(fadd(fdiv(x, Is), 1)))
        ], [0, fdiv(Vcc, R)], [0, Vcc])
Exemplo n.º 16
0
def main():
  parser = argparse.ArgumentParser(description='Analyse Parallel Diode')
  parser.add_argument('Vs', type=float, help='Voltage supply')
  parser.add_argument('R1', type=float, help='Resistor 1 value in Ohms')
  parser.add_argument('R2', type=float, help='Resistor 2 value in Ohms')
  parser.add_argument('Is', type=float, nargs='?', default=1e-12, help='Diode Saturation current in Amps (default = 1e-12)')
  parser.add_argument('N', type=float, nargs='?', default=1, help='Emission Coefficient (default = 1)')
  parser.add_argument('--Vt', type=float, default=0.026, help='Thermal Voltage in Volts (default = 0.026)')
  parser.add_argument('-g', '--graph', action='store_true', help='Draw a graph')
  parser.add_argument('-v', '--verbose', action='store_true', help='Print debug')
  args = parser.parse_args()

  Vs = args.Vs
  R1 = args.R1
  R2 = args.R2
  Is = args.Is
  N = args.N
  Vt = args.Vt
  nVt = N*Vt

  if args.verbose:
    logging.basicConfig(format='%(levelname)s|%(message)s', level=logging.INFO)
  logging.info(f'Vs: {Vs}, R1: {R1}, R2: {R2}, Is: {Is}, N: {N}, Vt: {Vt}')

  x = fdiv(fmul(fmul(fmul(R1,R2),Is),exp(fdiv(fmul(R2,fadd(Vs,fmul(Is,R1))),(fmul(nVt,fadd(R1,R2)))))),fmul(nVt,fadd(R1,R2)))
  w = lambertw(x)
  Id = fsub(fdiv(fmul(fmul(nVt,w),fadd(R1,R2)),fmul(R1,R2)),Is)
  Vd = fmul(log(fadd(fdiv(Id,Is),mpf(1))),nVt)
  Rd = fdiv(Vd,Id)
  Rd2 = fdiv(fmul(Rd,R2),fadd(Rd,R2))
  VR2 = Vd
  IR2 = fdiv(VR2,R2)
  VR1 = fsub(Vs,Vd)
  IR1 = fdiv(VR1,R1)
  print("VR1: {}, IR1: {}".format(VR1, IR1))
  print("VR2: {}, IR2: {}".format(VR2, IR2))
  print("Vd: {}, Id: {}".format(Vd, Id))
  if args.graph:
    plot([lambda x: fsub(Vs,fmul(fadd(x,fdiv(fmul(nVt,log(fadd(fdiv(x,Is),mpf(1)))),R2)),R1)), lambda x: fmul(nVt,log(fadd(fdiv(x,Is),mpf(1))))], [0, fdiv(Vs,fadd(R1,Rd2))], [0, Vs])
Exemplo n.º 17
0
def exp_fixpoint(b=e,k=1,prec=53,iprec=None):
    """
    Counting fixpoints as follows:

    For b<=e^(1/e): 
      0 denotes the lower fixpoint on the real axis,
      1 denotes the upper fixed point on the real axis,
      2 denotes the fixpoint in the upper halfplane closest to the real axis, 
      3 the second-closest, etc

    For b>e^(1/e): 
      1 denotes the fixpoint in the upper halfplane closest to the real axis,
      2 the second-closest fixed point, etc.

    Or in other words order the repelling fixed points of the upper halfplane 
    by their distance from the real axis, give the closest fixed point the number 1.
    The attracting fixed point (existent only for b<e**(1/e)) gets index 0.

    Fixpoint k mirrored into the lower halfplane gets index -k.
    """
    if iprec==None:
        iprec=prec+10

    b=num(b,iprec)

    if k==0:
        assert b <= e**(1/e), "b must be <= e**(1/e) for fixpoint number 0, but b=" + repr(b)
    if k>=0:
        branch = -k
    elif b <= e**(1/e) and k==-1:
        branch = -1
    else:
        branch = -k-1

    mpmath.mp.prec = iprec
    fp = mpmath.lambertw(-mpmath.ln(b),branch)/(-mpmath.ln(b))
    if type(fp) == sage.libs.mpmath.ext_main.mpf:
      return num(fp,prec)
    return ComplexField(prec)(fp.real,fp.imag)
Exemplo n.º 18
0
def main(argv):
    if len(argv) != 5:
        print "Analyse Parallel Diode"
        print "Usage: apd <Vcc> <R1> <R2> <Is> <nVt>"
    else:
        Vcc = mpf(argv[0])
        R1 = mpf(argv[1])
        R2 = mpf(argv[2])
        Is = mpf(argv[3])
        nVt = mpf(argv[4])
        x = fdiv(
            fmul(
                fmul(fmul(R1, R2), Is),
                exp(
                    fdiv(fmul(R2, fadd(Vcc, fmul(Is, R1))),
                         (fmul(nVt, fadd(R1, R2)))))), fmul(nVt, fadd(R1, R2)))
        w = lambertw(x)
        Id = fsub(fdiv(fmul(fmul(nVt, w), fadd(R1, R2)), fmul(R1, R2)), Is)
        Vd = fmul(log(fadd(fdiv(Id, Is), mpf(1))), nVt)
        Rd = fdiv(Vd, Id)
        Rd2 = fdiv(fmul(Rd, R2), fadd(Rd, R2))
        VR2 = Vd
        IR2 = fdiv(VR2, R2)
        VR1 = fsub(Vcc, Vd)
        IR1 = fdiv(VR1, R1)
        print "VR1: {}, IR1: {}".format(VR1, IR1)
        print "VR2: {}, IR2: {}".format(VR2, IR2)
        print "Vd: {}, Id: {}".format(Vd, Id)
        plot([
            lambda x: fsub(
                Vcc,
                fmul(
                    fadd(x, fdiv(fmul(nVt, log(fadd(fdiv(x, Is), mpf(1)))), R2)
                         ), R1)),
            lambda x: fmul(nVt, log(fadd(fdiv(x, Is), mpf(1))))
        ], [0, fdiv(Vcc, fadd(R1, Rd2))], [0, Vcc])
Exemplo n.º 19
0
def getLambertW( n ):
    return lambertw( n )
Exemplo n.º 20
0
def getSuperRootOperator(n, k):
    '''Returns the positive, real kth super root of n.'''
    k = fsub(k, 1)
    value = fmul(k, log(n))
    return root(fdiv(value, lambertw(value)), k)
Exemplo n.º 21
0
 def eval(self, z):
     return mpmath.lambertw(z)
Exemplo n.º 22
0
def getSuperRoots( n, k ):
    k = fsub( real_int( k ), 1 )
    factors = [ fmul( i, root( k, k ) ) for i in unitroots( int( k ) ) ]
    base = root( fdiv( log( n ), lambertw( fmul( k, log( n ) ) ) ), k )

    return [ fmul( i, base ) for i in factors ]
Exemplo n.º 23
0
def test_issue_17898():
    if not scipy:
        skip("scipy not installed")
    x = symbols("x")
    f_ = lambdify([x], sympy.LambertW(x, -1), modules='scipy')
    assert f_(0.1) == mpmath.lambertw(0.1, -1)
Exemplo n.º 24
0
def getLambertWOperator(n):
    return lambertw(n)
Exemplo n.º 25
0
 def test_lambertw(self):
     assert_mpmath_equal(lambda x, k: sc.lambertw(x, int(k)),
                         lambda x, k: mpmath.lambertw(x, int(k)),
                         [Arg(), IntArg(0, 10)])
Exemplo n.º 26
0
def getCubeSuperRootOperator(n):
    '''Returns the positive, real cube super root of n.'''
    value = fmul(2, log(n))
    return sqrt(fdiv(value, lambertw(value)))
Exemplo n.º 27
0
def f77(x):
    # lambert_W0
    return mpmath.lambertw(x)
Exemplo n.º 28
0
def f78(x):
    # lambert_Wm1
    if x >= 0:
        return mpmath.lambertw(x)
    else:
        return mpmath.lambertw(x, -1)
Exemplo n.º 29
0
  def __init__(self,n,symbolic=False,iprec=53,prec=53,N=10,pred=None):
    self.N = N
    self.iprec = iprec
    self.prec = prec
    mp.prec = iprec
  
    L = PolynomialRing(QQ,'ln2')
    ln2 = L.gen()
    self.ln2 = ln2
    FPL = FormalPowerSeriesRing(L)
    self.FPL = FPL
  
    R = RealField(iprec)
    self.R = R
    FPR = FormalPowerSeriesRing(R)
    self.FPR = FPR
  
    def log2(x):
      return ln(x)/R(ln(2))

    if n==1:
      self.hfop = lambda x,y: log2(R(2)**x+R(2)**y)
      self.hp = FPL([1,1])
      self.hf = lambda x: x+1
      self.hfi = lambda x: x-1
      self.op = lambda x,y: x+y 
    elif n==2:
      self.hfop = lambda x,y: x + y
      self.hp = FPL([0,2])
      self.hf = lambda x: R(2)*x
      self.hfi = lambda x: x/R(2)
      self.op = lambda x,y: x*y # 2**(log2(x)+log2(y))
    elif n==3:
      self.hfop = lambda x,y: x*(R(2)**y)
      self.hp = FPL.Exp(FPL([0,ln2])) * FPL([0,1])
      self.hp.reclass()
      self.hpr = FPR.Exp(FPR([0,R(ln(2))])) * FPR([0,1])
      self.hpr.reclass()
      self.hf = lambda x: R(x)*R(2)**R(x)
      self.hfi = lambda y: R(lambertw(R(y)*R(ln(2))))/R(ln(2))
      self.op = lambda x,y: x**y
    else:
      if pred != None: self.G = pred
      else:
        self.G = Balanced(n-1,symbolic=symbolic,iprec=iprec,prec=prec,N=N)
      self.hpop = lambda y: self.G.hp.it(y)
      self.hp = self.G.hp.selfit()
      self.hp.reclass()
      if symbolic:
        def subs(e): 
          if type(e) == int:
            return R(e) 
          return e.subs(R( log( 2 ) ))
        self.hprop = lambda y: FPR.by_formal_powerseries(self.hpop(y),subs)
        self.hpr = FPR.by_formal_powerseries(self.hp, subs)
      else:
        self.hprop = lambda y: self.G.hpr.it(y)
        self.hpr = self.G.hpr.selfit()
      self.hpr.reclass()
      self.hfop = self.f()
      self.hf = lambda x: self.hfop(x,x)
      #self.hfi = self.f(self.hp.inv())
      self.op = lambda x,y: R(2)**(self.hfop(log2(x),log2(y)))
Exemplo n.º 30
0
 'expjpi': ['primitive', [lambda x, y: mp.expjpi(x), None]],  #exp(x*i*pi)
 'expm1': ['primitive', [lambda x, y: mp.expm1(x), None]],  #exp(x)-1
 'power': ['primitive', [lambda x, y: mp.power(x, y[0]), None]],
 'powm1': ['primitive', [lambda x, y: mp.powm1(x, y[0]),
                         None]],  #pow(x, y) - 1 
 'log': [
     'primitive',
     [lambda x, y: mp.log(x) if y is None else mp.log(x, y[0]), None]
 ],
 'ln': ['primitive', [lambda x, y: mp.ln(x), None]],
 'log10': ['primitive', [lambda x, y: mp.log10(x), None]],
 #
 'lambertw': [
     'primitive',
     [
         lambda x, y: mp.lambertw(x)
         if y is None else mp.lambertw(x, y[0]), None
     ]
 ],
 'agm': [
     'primitive',
     [lambda x, y: mp.agm(x) if y is None else mp.agm(x, y[0]), None]
 ],
 #
 'matrix': [
     'primitive',
     [
         lambda x, y: mp.matrix(x) if isa(x, Vector) else mp.matrix(x)
         if y is None else mp.matrix(x, y[0]), None
     ]
 ],
Exemplo n.º 31
0
def lambertPos(x, factor):
    x, factor = [Decimal(value) for value in vars().values()]
    return Decimal(str(lambertw(+x / factor))) / (+x / factor) * factor
Exemplo n.º 32
0
 def eval(self, z):
     return mpmath.lambertw(z)
Exemplo n.º 33
0
from decimal import Decimal
from decimal import getcontext
from common.constants import MAX_PRECISION
from common.constants import LAMBERT_POS2_EXTENT
from common.constants import LAMBERT_POS2_SAMPLES

getcontext().prec = mp.dps = 100

LAMBERT_CONV_RADIUS = int(Decimal(-1).exp() * 2**MAX_PRECISION)
LAMBERT_POS2_SAMPLE = LAMBERT_POS2_EXTENT * 2**MAX_PRECISION // (
    LAMBERT_POS2_SAMPLES - 1)

samples = [
    Decimal(LAMBERT_CONV_RADIUS + 1 + LAMBERT_POS2_SAMPLE * i)
    for i in range(LAMBERT_POS2_SAMPLES)
]
lambertArray = [
    int(
        Decimal(str(lambertw(x / 2**MAX_PRECISION))) / (x / 2**MAX_PRECISION) *
        2**MAX_PRECISION) for x in samples
]

len1 = len(str(LAMBERT_POS2_SAMPLES))
len2 = len(hex(max(lambertArray)))

print('    function initLambertArray() internal {')
for n in range(len(lambertArray)):
    print('        lambertArray[{0:{1}d}] = {2:#0{3}x};'.format(
        n, len1, lambertArray[n], len2))
print('    }')
Exemplo n.º 34
0
 def test_lambertw(self):
     assert_mpmath_equal(lambda x, k: sc.lambertw(x, int(k)),
                         lambda x, k: mpmath.lambertw(x, int(k)),
                         [Arg(), IntArg(0, 10)])
Exemplo n.º 35
0
def getSquareSuperRoot( n ):
    return power( e, lambertw( log( n ) ) )
Exemplo n.º 36
0
def getSquareSuperRootOperator(n):
    '''Returns the positive, real square super root of n.'''
    return power(e, lambertw(log(n)))
Exemplo n.º 37
0
def getCubeSuperRoot( n ):
    value = fmul( 2, log( n ) )
    return sqrt( fdiv( value, lambertw( value ) ) )
Exemplo n.º 38
0
def mpmath_wrightomega(x):
    return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5'))
Exemplo n.º 39
0
def getSuperRoot( n, k ):
    k = fsub( real_int( k ), 1 )
    value = fmul( k, log( n ) )
    return root( fdiv( value, lambertw( value ) ), k )
Exemplo n.º 40
0
def lambertw(x):
    num = mpmath.lambertw(x)
    return num
Exemplo n.º 41
0
def lambertNeg(x, precision):
    x, precision = [Decimal(value) for value in vars().values()]
    return Decimal(str(lambertw(
        -x / 2**precision))) / (-x / 2**precision) * 2**precision