Example #1
0
def falsi(f, a, b, tol=1.0e-9):
    fa = f(a)
    if fa == 0.0: return a
    fb = f(b)
    if fb == 0.0: return b
    if sign(fa) == sign(fb): error.err('Root is not bracketed')
    for i in range(30):
        # Compute the improved root x from falsi formula

        s = b - fb * (b - a) / (fb - fa)
        fx = f(s)
        print(i + 1, '{0:8.6f}'.format(a), '{0:8.6f}'.format(b),
              '{0:8.6f}'.format(s), '{0:8.6f}'.format(fx))
        if s == 0.0: return None

        # Test for convergence
        if i > 0:
            if abs(fx) < tol:
                print('regula falsi has coverged')
                return s

    # Re-bracket the root as tightly as possible
        if sign(fx) != sign(fa):
            b = s
            fb = fx
        else:
            a = s
            fa = fx

    return None
    print('Too many iterations')
Example #2
0
def gaussJordanPivot(a, tol=1.0e-9):
    n = len(a)
    seq = array(range(n))

    # Set up scale factors
    s = zeros((n), type=Float64)
    for i in range(n):
        s[i] = max(abs(a[i, :]))

    for i in range(n):

        # Row interchange, if needed
        p = int(argmax(abs(a[i:n, i]) / s[i:n])) + i
        if abs(a[p, i]) < tol: error.err('Matrix is singular')
        if p != i:
            swap.swapRows(s, i, p)
            swap.swapRows(a, i, p)
            swap.swapRows(seq, i, p)

    # Elimination phase
        temp = a[i, i]
        a[i, i] = 1.0
        a[i, 0:n] = a[i, 0:n] / temp
        for k in range(n):
            if k != i:
                temp = a[k, i]
                a[k, i] = 0.0
                a[k, 0:n] = a[k, 0:n] - a[i, 0:n] * temp

# Rearrange columns in the right sequence
    for i in range(n):
        swap.swapCols(a, i, seq[i])
        swap.swapRows(seq, i, seq[i])
    return a
Example #3
0
def r():
    print("<<run_app>>")
    print("0) help()")
    print("1) calcbasic()")
    print("2) calcrand()")
    print("3) main()")
    print("4) err()")
    print("5) err()_alt")
    print("6) quit")
    import helpapp as hlp
    import error as er
    import sys as s
    isofflineplatform = 1
    a = int(input("q:"))
    if a == 0:
      hlp.help(isofflineplatform, debug)
    elif a == 1:
        calcbasic(10890, "+", 28753)
        calcbasic(10890, "-", 28753)
        calcbasic(10890, "*", 28753)
        calcbasic(10890, "/", 28753)
        calcbasic(10890, "/", 0)
    elif a == 2:
        calcrand(5475, -2300, 2354444)
    elif a == 3:
        main()
    elif a == 4:
        er.err("0x004", "SAMPLE_TEXT", "f", 1)
    elif a == 5:
        er.err("0x004", "SAMPLE_TEXT", "c", 1)
    elif a == 6:
      s.exit()
    s.exit()
Example #4
0
def gaussPivot(a,b,tol=1.0e-12):
    n = len(b)
# Mengatur faktor skala
    s = np.zeros(n)
    for i in range(n):
        s[i] = max(np.abs(a[i,:]))
    for k in range(0,n-1):
# menukar baris
        p = np.argmax(np.abs(a[k:n,k])/s[k:n]) + k
        if abs(a[p,k]) < tol: error.err('Tidak dapat dihitung : matriks singular')
        if p != k:
            swap.swapRows(b,k,p)
            swap.swapRows(s,k,p)
            swap.swapRows(a,k,p)
# Eliminasi
        for i in range(k+1,n):
            if a[i,k] != 0.0:
                lam = a[i,k]/a[k,k]
                a[i,k+1:n] = a[i,k+1:n] - lam*a[k,k+1:n]
                b[i] = b[i] - lam*b[k]
    if abs(a[n-1,n-1]) < tol: error.err('Tidak dapat dihitung : matriks singular')
# Substutisi kembali untuk mencari nilai variabel
    b[n-1] = b[n-1]/a[n-1,n-1]
    for k in range(n-2,-1,-1):
        b[k] = (b[k] - np.dot(a[k,k+1:n],b[k+1:n]))/a[k,k]
    return b
Example #5
0
def bisection(f, x1, x2, switch=1, tol=1.0e-9):
    f1 = f(x1)
    if f1 == 0.0: return x1
    f2 = f(x2)
    if f2 == 0.0: return x2
    if sign(f1) == sign(f2):
        error.err('Root is not bracketed')
    n = int(math.ceil(math.log(abs(x2 - x1) / tol) / math.log(2.0)))

    for i in range(n):
        x3 = 0.5 * (x1 + x2)
        f3 = f(x3)
        print('{0:6.4f}'.format(x1), '{0:8.6f}'.format(x2),
              '{0:8.6f}'.format(x3), '{0:8.6f}'.format(f1),
              '{0:8.6f}'.format(f2), '{0:8.6f}'.format(f3))
        if (switch == 1) and (abs(f3) > abs(f1)) \
                         and (abs(f3) > abs(f2)):
            return None
        if f3 == 0.0: return x3
        if sign(f2) != sign(f3):
            x1 = x3
            f1 = f3
        else:
            x2 = x3
            f2 = f3
    return (x1 + x2) / 2.0
Example #6
0
def brent(f,a,b,tol=1.0e-9):
    x1 = a; x2 = b;
    f1 = f(x1)
    if f1 == 0.0: return x1
    f2 = f(x2)
    if f2 == 0.0: return x2
    if f1*f2 > 0.0: error.err('Root is not bracketed')
    x3 = 0.5*(a + b)    
    for i in range(30):
        f3 = f(x3)
        if abs(f3) < tol: return x3
      # Tighten the brackets on the root
        if f1*f3 < 0.0: b = x3       
        else: a = x3
        if (b - a) < tol*max(abs(b),1.0): return 0.5*(a + b)
      # Try quadratic interpolation
        denom = (f2 - f1)*(f3 - f1)*(f2 - f3)
        numer = x3*(f1 - f2)*(f2 - f3 + f1)       \
              + f2*x1*(f2 - f3) + f1*x2*(f3 - f1)
      # If division by zero, push x out of bounds
        try: dx = f3*numer/denom
        except ZeroDivisionError: dx = b - a
        x = x3 + dx
      # If iterpolation goes out of bounds, use bisection  
        if (b - x)*(x - a) < 0.0:
            dx = 0.5*(b - a)
            x = a + dx
      # Let x3 <-- x & choose new x1 and x2 so that x1 < x3 < x2         
        if x < x3:        
            x2 = x3; f2 = f3        
        else:              
            x1 = x3; f1 = f3
        x3 = x                      
    print 'Too many iterations in brent'
Example #7
0
def LUdecomp(a, tol=1.0e-9):
    n = len(a)
    seq = array(range(n))

    # Set up scale factors
    s = zeros((n), dtype=float64)
    for i in range(n):
        s[i] = max(abs(a[i, :]))

    for k in range(0, n - 1):

        # Row interchange, if needed
        p = int(argmax(abs(a[k:n, k]) / s[k:n])) + k
        if abs(a[p, k]) < tol: error.err('Matrix is singular')
        if p != k:
            swap.swapRows(s, k, p)
            swap.swapRows(a, k, p)
            swap.swapRows(seq, k, p)

    # Elimination
        for i in range(k + 1, n):
            if a[i, k] != 0.0:
                lam = a[i, k] / a[k, k]
                a[i, k + 1:n] = a[i, k + 1:n] - lam * a[k, k + 1:n]
                a[i, k] = lam
    return a, seq
Example #8
0
def ridder(f,a,b,tol=1.0e-9):
    fa = f(a)
    if fa == 0.0: return a
    fb = f(b)
    if fb == 0.0: return b
    if sign(fa) == sign(fb): error.err('Root is not bracketed')
    for i in range(30):
        # Compute the improved root x from Ridder's formula
        c = 0.5*(a + b); fc = f(c)
        s = math.sqrt(fc**2 - fa*fb)
        if s == 0.0: return None
        dx = (c - a)*fc/s
        if (fa - fb) < 0.0: dx = -dx 
        x = c + dx; fx = f(x)
        # Test for convergence
        if i > 0:
            if abs(x - xOld) < tol*max(abs(x),1.0): return x
        xOld = x
        # Re-bracket the root as tightly as possible
        if sign(fc) == sign(fx): 
            if sign(fa)!= sign(fx): b = x; fb = fx
            else: a = x; fa = fx
        else:
            a = c; b = x; fa = fc; fb = fx
    return None
    print('Too many iterations')
Example #9
0
def newtonRaphson(f,df,a,b,tol=1.0e-9):
    import error
    fa = f(a)
    if fa == 0.0: return a
    fb = f(b)
    if fb == 0.0: return b
    if fa*fb > 0.0: error.err('Root is not bracketed')
    x = 0.5*(a + b)                    
    for i in range(30):
        fx = f(x)
        if abs(fx) < tol: return x
      # Tighten the brackets on the root 
        if fa*fx < 0.0:
            b = x  
        else:                  
            a = x; fa = fx
      # Try a Newton-Raphson step    
        dfx = df(x)
      # If division by zero, push x out of bounds
        try: dx = -fx/dfx
        except ZeroDivisionError: dx = b - a
        x = x + dx
      # If the result is outside the brackets, use bisection  
        if (b - x)*(x - a) < 0.0:  
            dx = 0.5*(b-a)                      
            x = a + dx
      # Check for convergence     
        if abs(dx) < tol*max(abs(b),1.0): return x
    print 'Too many iterations in Newton-Raphson'
Example #10
0
 def isNextTo(self, v, w): #checks if two edges are next to each other
     if not(v < self._V and w < self._V):
         error.err("Graph does not contain this edge.")
     for i in self._nextTo[v]:
         if i == w:
             return True
     return False
Example #11
0
def gaussPivot(a,b,tol=1.0e-12):
    n = len(b)
    
  # Set up scale factors
    s = zeros((n),type=Float64)
    for i in range(n):
        s[i] = max(abs(a[i,:]))
            
    for k in range(0,n-1):
        
      # Row interchange, if needed
        p = int(argmax(abs(a[k:n,k])/s[k:n])) + k
        if abs(a[p,k]) < tol: error.err('Matrix is singular')
        if p != k:
            swap.swapRows(b,k,p)
            swap.swapRows(s,k,p)
            swap.swapRows(a,k,p)
            
      # Elimination
        for i in range(k+1,n):
            if a[i,k] != 0.0:
                lam = a[i,k]/a[k,k]
                a[i,k+1:n] = a [i,k+1:n] - lam*a[k,k+1:n]
                b[i] = b[i] - lam*b[k]
    if abs(a[n-1,n-1]) < tol: error.err('Matrix is singular')
                   
  # Back substitution
    for k in range(n-1,-1,-1):
        b[k] = (b[k] - dot(a[k,k+1:n],b[k+1:n]))/a[k,k]
    return b
Example #12
0
def bisectionx(f, x1, x2, switch=1, tol=1.0e-9):
    logdat = []
    f1 = f(x1)
    if f1 == 0.0: return x1, logdat
    f2 = f(x2)
    if f2 == 0.0: return x2, logdat
    if sign(f1) == sign(f2):
        error.err('Root is not bracketed')
    n = int(math.ceil(math.log(abs(x2 - x1) / tol) / math.log(2.0)))

    for i in range(n):
        x3 = 0.5 * (x1 + x2)
        f3 = f(x3)
        #print('{0:6.4f}'.format(x1),'{0:8.6f}'.format(x2),'{0:8.6f}'.format(x3),'{0:8.6f}'.format(f1),'{0:8.6f}'.format(f2),'{0:8.6f}'.format(f3))
        logdat.append([
            round(x1, 4),
            round(x2, 4),
            round(x3, 4),
            round(f1, 4),
            round(f2, 4),
            round(f3, 4)
        ])
        if (switch == 1) and (abs(f3) > abs(f1)) \
                         and (abs(f3) > abs(f2)):
            return None, logdat
        if f3 == 0.0: return x3, logdat
        if sign(f2) != sign(f3):
            x1 = x3
            f1 = f3
        else:
            x2 = x3
            f2 = f3
    return (x1 + x2) / 2.0, logdat
Example #13
0
def ridder(f, a, b, tol=1.0e-9):
    fa = f(a)
    if fa == 0.0: return a
    fb = f(b)
    if fb == 0.0: return b
    if fa * fb > 0.0: error.err('Root is not bracketed')
    for i in range(30):
        # Compute the improved root x from Ridder's formula
        c = 0.5 * (a + b)
        fc = f(c)
        s = sqrt(fc**2 - fa * fb)
        if s == 0.0: return None
        dx = (c - a) * fc / s
        if (fa - fb) < 0.0: dx = -dx
        x = c + dx
        fx = f(x)
        # Test for convergence
        if i > 0:
            if abs(x - xOld) < tol * max(abs(x), 1.0): return x
        xOld = x
        # Re-bracket the root as tightly as possible
        if fc * fx > 0.0:
            if fa * fx < 0.0:
                b = x
                fb = fx
            else:
                a = x
                fa = fx
        else:
            a = c
            b = x
            fa = fc
            fb = fx
    return None
    print('Too many iterations')
Example #14
0
def LUdecomp(a, tol=1.0e-9):
    n = len(a)
    seq = array(range(n))

    # Set up scale factors
    s = zeros((n), type=Float64)
    for i in range(n):
        s[i] = max(abs(a[i, :]))

    for k in range(0, n - 1):

        # Row interchange, if needed
        p = int(argmax(abs(a[k:n, k]) / s[k:n])) + k
        if abs(a[p, k]) < tol:
            error.err("Matrix is singular")
        if p != k:
            swap.swapRows(s, k, p)
            swap.swapRows(a, k, p)
            swap.swapRows(seq, k, p)

        # Elimination
        for i in range(k + 1, n):
            if a[i, k] != 0.0:
                lam = a[i, k] / a[k, k]
                a[i, k + 1 : n] = a[i, k + 1 : n] - lam * a[k, k + 1 : n]
                a[i, k] = lam
    return a, seq
Example #15
0
def guassPivot(a,b,tol=1.0e-12):
    n = len(b)
    
    s = np.zeros(n)
    for i in range(n):
        s[i] = max(np.abs(a[i,:]))

    for k in range(0,n-1):
        p = np.argmax(np.abs(a[k:n,k]) / s[k:n]) + k
        if abs(a[p,k]) < tol: error.err('Matrix is Singular'):
        if p != k:
            swap.swapRows(b, k, p)
            swap.swapRows(s, k, p)
            swap.swapRows(a, k, p)
         
    for i in range(k+1,n):
        if a[i,k] != 0.0:
            lam = a[i,k]/a[k,k]
            a[i,k+1:n] = a[i, k+1:n] - lam*a[k, k+1:n]
            b[i] = b[i] - lam*b[k]
            
    if abs(a[n-1,n-1)]) < tol: error.err('Matrix is Singular'):
        
    b[n-1] = b[n-1]/a[n-1,n-1]
    for k in range(n-1, -1,-1):
        b[k] = (b[k]- np.dot(a[k,k+1:n], b[k+1:n]))/a[k,k]
Example #16
0
def gaussPivot(a, b, tol=1.0e-12):
    n = len(b)

    # Set up scale factors
    s = zeros((n), dtype=float64)
    for i in range(n):
        s[i] = max(abs(a[i, :]))

    for k in range(0, n - 1):

        # Row interchange, if needed
        p = int(argmax(abs(a[k:n, k]) / s[k:n])) + k
        if abs(a[p, k]) < tol: error.err('Matrix is singular')
        if p != k:
            swap.swapRows(b, k, p)
            swap.swapRows(s, k, p)
            swap.swapRows(a, k, p)

    # Elimination
        for i in range(k + 1, n):
            if a[i, k] != 0.0:
                lam = a[i, k] / a[k, k]
                a[i, k + 1:n] = a[i, k + 1:n] - lam * a[k, k + 1:n]
                b[i] = b[i] - lam * b[k]
    if abs(a[n - 1, n - 1]) < tol: error.err('Matrix is singular')

    # Back substitution
    for k in range(n - 1, -1, -1):
        b[k] = (b[k] - dot(a[k, k + 1:n], b[k + 1:n])) / a[k, k]
    return b
Example #17
0
def gaussJordanPivot(a,tol=1.0e-9):
    n = len(a)
    seq = array(range(n))
    
  # Set up scale factors
    s = zeros((n),type=Float64)
    for i in range(n):
        s[i] = max(abs(a[i,:]))      
    
    for i in range(n):

      # Row interchange, if needed
        p = int(argmax(abs(a[i:n,i])/s[i:n])) + i
        if abs(a[p,i]) <  tol: error.err('Matrix is singular')
        if p != i:
            swap.swapRows(s,i,p)
            swap.swapRows(a,i,p)
            swap.swapRows(seq,i,p)
            
      # Elimination phase
        temp = a[i,i]
        a[i,i] = 1.0
        a[i,0:n] = a[i,0:n]/temp
        for k in range(n):
            if k != i: 
                temp = a[k,i]
                a[k,i] = 0.0
                a[k,0:n] = a[k,0:n] - a[i,0:n]*temp

  # Rearrange columns in the right sequence
    for i in range(n):
        swap.swapCols(a,i,seq[i])
        swap.swapRows(seq,i,seq[i])
    return a
Example #18
0
def newtonRaphson(f, df, a, b, tol=1.0e-9):
    import error
    fa = f(a)
    if fa == 0.0: return a
    fb = f(b)
    if fb == 0.0: return b
    if fa * fb > 0.0: error.err('Root is not bracketed')
    x = 0.5 * (a + b)
    for i in range(30):
        fx = f(x)
        if abs(fx) < tol: return x
        # Tighten the brackets on the root
        if fa * fx < 0.0:
            b = x
        else:
            a = x
            fa = fx
    # Try a Newton-Raphson step
        dfx = df(x)
        # If division by zero, push x out of bounds
        try:
            dx = -fx / dfx
        except ZeroDivisionError:
            dx = b - a
        x = x + dx
        # If the result is outside the brackets, use bisection
        if (b - x) * (x - a) < 0.0:
            dx = 0.5 * (b - a)
            x = a + dx
    # Check for convergence
        if abs(dx) < tol * max(abs(b), 1.0): return x
    print 'Too many iterations in Newton-Raphson'
Example #19
0
def remoteCommandFactory(destination, params):
  """Depending in the method, instantiate a corresponding
  RemoteCommand derived object and return it"""

  method = params['method']
  try:
    return _remoteCommandPlugins[method](destination, params)
  except KeyError:
    error.err('Method not implemented: "%s"' % method)
Example #20
0
def remoteCommandFactory(destination, params):
    """Depending in the method, instantiate a corresponding
	RemoteCommand derived object and return it"""

    method = params['method']
    try:
        return _remoteCommandPlugins[method](destination, params)
    except KeyError:
        error.err('Method not implemented: "%s"' % method)
Example #21
0
def LUpivotSolve(a,b,seq, tol=1.0e-9):
    n = len(b)
    for k in range(1,n):        ##Forward
        b[k] -= float(dot(a[k,0:k], b[0:k]))
    
    for k in range(n-1,-1,-1):  ##Backward
        if abs(a[k,k]) < tol: error.err('Matrix is singular')
        b[k] = float(b[k] - dot(a[k,k+1:n], b[k+1:n]))/a[k,k]
        
    return b
Example #22
0
def choleski(a):
    n = len(a)
    for k in range(n):
        try:
            a[k,k] = sqrt(a[k,k] - dot(a[k,0:k],a[k,0:k]))
        except ValueError:
            error.err('Matrix is not positive definite')
        for i in range(k+1,n):
            a[i,k] = (a[i,k] - dot(a[i,0:k],a[k,0:k]))/a[k,k]
    for k in range(1,n): a[0:k,k] = 0.0
    return a
def choleski(a):
    n = len(a)
    for k in range(n):
        try:
            a[k,k] = sqrt(a[k,k] - dot(a[k,0:k],a[k,0:k]))
        except ValueError:
            error.err('Matrix is not positive definite')
        for i in range(k+1,n):
            a[i,k] = (a[i,k] - dot(a[i,0:k],a[k,0:k]))/a[k,k]
    for k in range(1,n): a[0:k,k] = 0.0
    return a
Example #24
0
	def getGroupMembers(self, groupName):
		"Return list of groupName members with sub lists expanded recursively"

		g = self._getGroup(groupName)
		out = [ (x, self.getGroupParams(groupName)) for x in g["hosts"] ]
		for list in g["lists"]:
			try:
				out = out + self.getGroupMembers(list)
			except (KeyError, RuntimeError):
				if sys.exc_type == KeyError:
					error.warn("in group '%s': no such group '%s'" % (groupName, list))
				if sys.exc_type == RuntimeError:
					error.err("runtime error: possible loop in configuration file")
		return out
Example #25
0
    def path(self, v):
        if self._distTo[v] == -1:
            error.err("Vertex " + str(v) + " is not connected")
        queue = deque([v])
        k = v
        while self._edgeTo[k] != self._S:
            k = self._edgeTo[k]
            queue.append(k)
        
        paths = []
        queue.reverse()
        paths.append(self._S)

        for i in queue:
            paths.append(i)
        return paths
Example #26
0
def bisection(f,x1,x2,switch=1,tol=1.0e-9):
    f1 = f(x1)
    if f1 == 0.0: return x1
    f2 = f(x2)
    if f2 == 0.0: return x2
    if f1*f2 > 0.0: error.err('Root is not bracketed')
    n = ceil(log(abs(x2 - x1)/tol)/log(2.0))
    for i in range(n):
        x3 = 0.5*(x1 + x2); f3 = f(x3)
        if (switch == 1) and (abs(f3) > abs(f1)) \
                         and (abs(f3) > abs(f2)):
            return None   
        if f3 == 0.0: return x3
        if f2*f3 < 0.0: x1 = x3; f1 = f3
        else:           x2 = x3; f2 = f3
    return (x1 + x2)/2.0
def newtonRaphsonMOD(f, df, a, b, tol=1.0e-9):
    # NOTE: Modified to help create an animated plot for problem 4.1.18
    fa = f(a)
    if fa == 0.0: return a
    fb = f(b)
    if fb == 0.0: return b
    if fa * fb > 0.0: error.err('Root is not bracketed')
    x = 0.5 * (a + b)

    for i in range(30):
        fx = f(x)
        if abs(fx) < tol: return x
        # Tighten the brackets on the root
        if fa * fx < 0.0:
            b = x
        else:
            a = x
            fa = fx
    # Try a Newton-Raphson step
        dfx = df(x)

        # construct a tangent line, store pts for later animated plotting
        slope = dfx
        y = f(x)
        intercept = slope * (-1) * x + y
        ys = []
        for q in xs:
            y = slope * q + intercept  #tangent line eq in slope-icept form
            ys.append(y)
        all_ys.append(ys)

        # If division by zero, push x out of bounds
        try:
            dx = -fx / dfx
        except ZeroDivisionError:
            dx = b - a
        x = x + dx

        # If the result is outside the brackets, use bisection
        if (b - x) * (x - a) < 0.0:
            dx = 0.5 * (b - a)
            x = a + dx

    # Check for convergence
        all_xs.append(x)
        if abs(dx) < tol * max(abs(b), 1.0): return x
    print 'Too many iterations in Newton-Raphson'
Example #28
0
def bisectioninc(f,x1,x2,switch=1,tol=1.0e-9):
    f1 = f(x1)
    if f1 == 0.0: return x1
    f2 = f(x2)
    if f2 == 0.0: return x2
    if np.sign(f1) == np.sign(f2):
        error.err('Root is not bracketed')
    n = int(math.ceil(math.log(abs(x2 - x1)/tol)/math.log(2.0)))
    for i in range(n):
        x3 = 0.5*(x1 + x2); f3 = f(x3)
        if (switch == 1) and (abs(f3) > abs(f1)) \
            and (abs(f3) > abs(f2)):
                return None
        if f3 == 0.0: return x3
        if np.sign(f2)!= np.sign(f3): x1 = x3; f1 = f3
        else: x2 = x3; f2 = f3
    return (x1 + x2)/2.0
Example #29
0
def falsePos(f,xl,xu,tol=1.0e-9):
    fl = f(xl)
    if fl == 0.0: return xl
    fu = f(xu)
    if fu == 0.0: return xu
    if sign(fl) == sign(fu):
        error.err('erorr yaa')
    xr = 0.0
    for i in range(100):
        xrold = xr
        xr = xu - (fu*(xl-xu))/(fl-fu)
        fr = f(xr)
        if (fr==0.0 or abs(xrold-xr)<tol): return xr
        if sign(fu) != sign(fr):
            xl = xr;fl=fr
        else:
            xu=xr;fu=fr
def bisection(f,x1,x2,switch=1,tol=1.0e-9):
    f1 = f(x1)
    if f1 == 0.0: return x1
    f2 = f(x2)
    if f2 == 0.0: return x2
    if f1*f2 > 0.0: error.err('Root is not bracketed')
#    n = ceil(log(abs(x2 - x1)/tol)/log(2.0))
    n = int(log(abs(x2 - x1)/tol)/log(2.0))
    for i in range(n):
        x3 = 0.5*(x1 + x2); f3 = f(x3)
        if (switch == 1) and (abs(f3) > abs(f1)) \
                         and (abs(f3) > abs(f2)):
            return None   
        if f3 == 0.0: return x3
        if f2*f3 < 0.0: x1 = x3; f1 = f3
        else:           x2 = x3; f2 = f3
    return (x1 + x2)/2.0
Example #31
0
	def dump(self, file):
		"Save configuration to file"
		
		comment = [
		"#\n",
		"# CURRENT CONFIGURATION\n",
		"#\n",
		"# You can change the configuration for the current session here.\n",
		"# Those changes will be lost after you quit tentakel.\n",
		"# No configuration file will be changed.\n",
		"#\n"
		]

		try:
			file.writelines(comment)
			file.writelines(str(self))
		except IOError:
			error.err("could not write to file: '%s'" % file.name)
Example #32
0
def bisect(f, x1, x2, switch=0, epsilon=1.0e-9):
    f1 = f(x1)
    if f1 == 0.0: return x1
    f2 = f(x2)
    if f2 == 0.0: return x2
    if f1 * f2 > 0.0: error.err('Root is not bracketed')
    n = math.ceil(math.log(abs(x2 - x1) / epsilon) / math.log(2.0))
    for i in range(int(n)):
        x3 = 0.5 * (x1 + x2)
        f3 = f(x3)
        if (switch == 1) and (abs(f3) >abs(f1)) \
                         and (abs(f3) > abs(f2)):
            return None
        if f3 == 0.0: return x3
        if f2 * f3 < 0.0:
            x1 = x3
            f1 = f3
        else:
            x2 = x3
            f2 = f3
    return (x1 + x2) / 2.0
Example #33
0
def bisection(f, x1, x2, switch=1, tol=1.0e-9):
    f1 = f(x1)
    if f1 == 0.0: return x1
    f2 = f(x2)
    if f2 == 0.0: return x2
    if sign(f1) == sign(f2):
        error.err("Root is not bracketed")
    n = int(math.ceil(math.log(abs(x2 - x1) / tol) / math.log(2.0)))
    #print "Pasos: ", n
    for i in range(n):
        x3 = 0.5 * (x1 + x2)
        f3 = f(x3)
        if (switch == 1) and (abs(f3) > abs(f1)) and (abs(f3) > abs(f2)):
            return None
        if f3 == 0.0: return x3
        if sign(f2) != sign(f3):
            x1 = x3
            f1 = f3
        else:
            x2 = x3
            f2 = f3
    return (x1 + x2) / 2.0
Example #34
0
def brent(f, a, b, tol=1.0e-9):
    x1 = a
    x2 = b
    f1 = f(x1)
    if f1 == 0.0: return x1
    f2 = f(x2)
    if f2 == 0.0: return x2
    if f1 * f2 > 0.0: error.err('Root is not bracketed')
    x3 = 0.5 * (a + b)
    for i in range(30):
        f3 = f(x3)
        if abs(f3) < tol: return x3
        # Tighten the brackets on the root
        if f1 * f3 < 0.0: b = x3
        else: a = x3
        if (b - a) < tol * max(abs(b), 1.0): return 0.5 * (a + b)
        # Try quadratic interpolation
        denom = (f2 - f1) * (f3 - f1) * (f2 - f3)
        numer = x3*(f1 - f2)*(f2 - f3 + f1)       \
              + f2*x1*(f2 - f3) + f1*x2*(f3 - f1)
        # If division by zero, push x out of bounds
        try:
            dx = f3 * numer / denom
        except ZeroDivisionError:
            dx = b - a
        x = x3 + dx
        # If iterpolation goes out of bounds, use bisection
        if (b - x) * (x - a) < 0.0:
            dx = 0.5 * (b - a)
            x = a + dx
    # Let x3 <-- x & choose new x1 and x2 so that x1 < x3 < x2
        if x < x3:
            x2 = x3
            f2 = f3
        else:
            x1 = x3
            f1 = f3
        x3 = x
    print 'Too many iterations in brent'
def LUdecomp(a,tol=1.0e-9):
    n = len(a)
    seq = np.array(range(n))
    
  # Set up scale factors
    s = np.zeros((n))
    for i in range(n):
        s[i] = max(abs(a[i,:]))        
    
    for k in range(0,n-1):
        
      # Row interchange, if needed
        p = np.argmax(np.abs(a[k:n,k])/s[k:n]) + k
        if abs(a[p,k]) <  tol: error.err('Matrix is singular')
        if p != k:
            swap.swapRows(s,k,p)
            swap.swapRows(a,k,p)
            swap.swapRows(seq,k,p)
      # Elimination using outer product       
        a[k+1:,k] /=a[k,k]
        a[k+1:,k+1:] -=  np.outer(a[k+1:,k],a[k,k+1:])
    return a,seq
Example #36
0
def gaussPivot(a, b, tol=1.0e-12):
    n = len(b)

    # Set up scale factors
    s = np.zeros(n)
    for i in range(n):
        s[i] = max(np.abs(a[i, :]))

    for k in range(0, n - 1):

        # Row interchange, if needed
        p = np.argmax(np.abs(a[k:n, k]) / s[k:n]) + k
        if abs(a[p, k]) < tol: error.err('Matrix is singular')
        if p != k:
            swap.swapRows(b, k, p)
            swap.swapRows(s, k, p)
            swap.swapRows(a, k, p)

        # Elimination
        for i in range(k + 1, n):
            if a[i, k] != 0.0:
                lam = a[i, k] / a[k, k]
                a[i, k + 1:n] = a[i, k + 1:n] - lam * a[k, k + 1:n]
                b[i] = b[i] - lam * b[k]
    if abs(a[n - 1, n - 1]) < tol: error.err('Matrix is singular')

    # Back substitution
    b[n - 1] = b[n - 1] / a[n - 1, n - 1]
    for k in range(n - 2, -1, -1):
        b[k] = (b[k] - np.dot(a[k, k + 1:n], b[k + 1:n])) / a[k, k]
    return b


#A = np.array([[2.,-2.,6.],[-2.,4.,3.],[-1.,8.,4.]])
#B = np.array([16.,0.,-1.])

#X = gaussPivot(A,B)
#print('X = {0}'.format(X))
Example #37
0
def LUpivot(a1, b1, tol=1.0e-9, modifyOriginal=True):
##def LUpivot(a1, modifyOriginal=True):
    if modifyOriginal:
        a = a1
    else:
        a = a1.copy()
        
    n = len(a)
    seq = array(range(n))
    
  # Set up scale factors
    s = zeros(n)
    for i in range(n):
        s[i] = max(abs(a[i,:]))        
    
    for k in range(0,n-1):
        
      # Row interchange, if needed
        p = argmax(abs(a[k:n,k])/s[k:n]) + k
        if abs(a[p,k]) < tol: error.err('Matrix is singular')
        if p != k:
            swap.swapRows(s,k,p)
            swap.swapRows(a,k,p)
            swap.swapRows(seq,k,p)
            
      # Elimination            
        for i in range(k+1,n):
            if a[i,k] != 0.0:
                lam = a[i,k]/a[k,k]
                a[i,k+1:n] = a[i,k+1:n] - lam*a[k,k+1:n]
                a[i,k] = lam
                
    b = b1.copy()
    for i in range(n):
        b[i] = b1[seq[i]]
    return a,b,seq
Example #38
0
class ConfigBase(dict):
	"""Store all configuration parameters
	
	This class is used to hold a specific configuration state in a special
	tree that's built out of dictionaries and lists. Single parameters can
	be changed or asked for their values. The whole configuration can be
	changed by using the parse method on a string that contains configuration
	directives in a format suitable for tentakel. Alternatively the load
	method can be used directly on a file.

	The configuration can be written to a file with the dump method.
	"""

	def __init__(self):
		super(ConfigBase, self).__init__()
		self.clear()
	
	def clear(self):
		"Make configuration empty"
		self["groups"] = {}
		self["settings"] = PARAMS

	def parse(self, txt):
		"""Parse a string containing configuration directives into
		the configuration tree"""
		tp = TConf()
		self.update(tp(txt))
	
	def load(self, file):
		"Load configuration from file"
		
		try:
			self.parse("".join(file.readlines()))
		except tpg.SyntacticError, excerr:
			error.warn("in %s: %s" % (file.name, excerr.msg))
		except IOError:
			error.err("could not read from file: '%s'" % file.name)
Example #39
0
def socksend(sock, message):
    try:
        sock.send(message)
    except socket.error as e:
        error.err('SocketError', e.strerror)
Example #40
0
def registerRemoteCommandPlugin(method, cls):
  """Needs to be imported and executed by remote command plugins"""
  if RemoteCommand in cls.__bases__:
    _remoteCommandPlugins[method] = cls
  else:
    error.err('%s is not a descendant of RemoteCommand' % cls)
Example #41
0
 def distance(self, v):
     if self._distTo[v] == -1:
         error.err("Vertex " + str(v) + " is not connected")
     return self._distTo[v]