bugged
stringlengths 4
228k
| fixed
stringlengths 0
96.3M
| __index_level_0__
int64 0
481k
|
|---|---|---|
def vectors_by_length(self, bound): """ Returns a list of short vectors together with their values. This is a naive algorithm which uses the Cholesky decomposition, but does not use the LLL-reduction algorithm. INPUT: bound -- an integer >= 0 OUTPUT: A list L of length (bound + 1) whose entry L[i] is a list of all vectors of length i. Reference: This is a slightly modified version of Cohn's Algorithm 2.7.5 in "A Course in Computational Number Theory", with the increment step moved around and slightly re-indexed to allow clean looping. Note: We could speed this up for very skew matrices by using LLL first, and then changing coordinates back, but for our purposes the simpler method is efficient enough. =) EXAMPLES: sage: Q = DiagonalQuadraticForm(ZZ, [1,1]) sage: Q.vectors_by_length(5) [[[0, 0]], [[0, -1], [-1, 0]], [[-1, -1], [1, -1]], [], [[0, -2], [-2, 0]], [[-1, -2], [1, -2], [-2, -1], [2, -1]]] sage: Q1 = DiagonalQuadraticForm(ZZ, [1,3,5,7]) sage: Q1.vectors_by_length(5) [[[0, 0, 0, 0]], [[-1, 0, 0, 0]], [], [[0, -1, 0, 0]], [[-1, -1, 0, 0], [1, -1, 0, 0], [-2, 0, 0, 0]], [[0, 0, -1, 0]]] """ Theta_Precision = bound ## Unsigned long n = self.dim() ## Make the vector of vectors which have a given value ## (So theta_vec[i] will have all vectors v with Q(v) = i.) empty_vec_list = [[] for i in range(Theta_Precision + 1)] theta_vec = [[] for i in range(Theta_Precision + 1)] ## Initialize Q with zeros and Copy the Cholesky array into Q Q = self.cholesky_decomposition() ## 1. Initialize T = n * [RDF(0)] ## Note: We index the entries as 0 --> n-1 U = n * [RDF(0)] i = n-1 T[i] = RDF(Theta_Precision) U[i] = RDF(0) L = n * [0] x = n * [0] Z = RDF(0) ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) done_flag = False Q_val_double = RDF(0) Q_val = 0 ## WARNING: Still need a good way of checking overflow for this value... ## Big loop which runs through all vectors while not done_flag: ## 3b. Main loop -- try to generate a complete vector x (when i=0) while (i > 0): #print " i = ", i #print " T[i] = ", T[i] #print " Q[i][i] = ", Q[i][i] #print " x[i] = ", x[i] #print " U[i] = ", U[i] #print " x[i] + U[i] = ", (x[i] + U[i]) #print " T[i-1] = ", T[i-1] T[i-1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) #print " T[i-1] = ", T[i-1] #print " x = ", x #print i = i - 1 U[i] = 0 for j in range(i+1, n): U[i] = U[i] + Q[i][j] * x[j] ## Now go back and compute the bounds... ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) ## 4. Solution found (This happens when i = 0) #print "-- Solution found! --" #print " x = ", x #print " Q_val = Q(x) = ", Q_val Q_val_double = Theta_Precision - T[0] + Q[0][0] * (x[0] + U[0]) * (x[0] + U[0]) Q_val = ZZ(floor(round(Q_val_double))) ## SANITY CHECK: Roundoff Error is < 0.001 if abs(Q_val_double - Q_val) > 0.001: print " x = ", x print " Float = ", Q_val_double, " Long = ", Q_val raise RuntimeError, "The roundoff error is bigger than 0.001, so we should use more precision somewhere..." #print " Float = ", Q_val_double, " Long = ", Q_val, " XX " #print " The float value is ", Q_val_double #print " The associated long value is ", Q_val if (Q_val <= Theta_Precision): #print " Have vector ", x, " with value ", Q_val theta_vec[Q_val].append(deepcopy(x)) ## 5. Check if x = 0, for exit condition. =) j = 0 done_flag = True while (j < n): if (x[j] != 0): done_flag = False j += 1 ## 3a. Increment (and carry if we go out of bounds) x[i] += 1 while (x[i] > L[i]) and (i < n-1): i += 1 x[i] += 1 #print " Leaving ThetaVectors()" return theta_vec
|
def vectors_by_length(self, bound): """ Returns a list of short vectors together with their values. This is a naive algorithm which uses the Cholesky decomposition, but does not use the LLL-reduction algorithm. INPUT: bound -- an integer >= 0 OUTPUT: A list L of length (bound + 1) whose entry L[i] is a list of all vectors of length i. Reference: This is a slightly modified version of Cohn's Algorithm 2.7.5 in "A Course in Computational Number Theory", with the increment step moved around and slightly re-indexed to allow clean looping. Note: We could speed this up for very skew matrices by using LLL first, and then changing coordinates back, but for our purposes the simpler method is efficient enough. =) EXAMPLES: sage: Q = DiagonalQuadraticForm(ZZ, [1,1]) sage: Q.vectors_by_length(5) [[[0, 0]], [[0, -1], [-1, 0]], [[-1, -1], [1, -1]], [], [[0, -2], [-2, 0]], [[-1, -2], [1, -2], [-2, -1], [2, -1]]] sage: Q1 = DiagonalQuadraticForm(ZZ, [1,3,5,7]) sage: Q1.vectors_by_length(5) [[[0, 0, 0, 0]], [[-1, 0, 0, 0]], [], [[0, -1, 0, 0]], [[-1, -1, 0, 0], [1, -1, 0, 0], [-2, 0, 0, 0]], [[0, 0, -1, 0]]] """ Theta_Precision = bound ## Unsigned long n = self.dim() ## Make the vector of vectors which have a given value ## (So theta_vec[i] will have all vectors v with Q(v) = i.) empty_vec_list = [[] for i in range(Theta_Precision + 1)] theta_vec = [[] for i in range(Theta_Precision + 1)] ## Initialize Q with zeros and Copy the Cholesky array into Q Q = self.cholesky_decomposition() ## 1. Initialize T = n * [RDF(0)] ## Note: We index the entries as 0 --> n-1 U = n * [RDF(0)] i = n-1 T[i] = RDF(Theta_Precision) U[i] = RDF(0) L = n * [0] x = n * [0] Z = RDF(0) ## 2. Compute bounds Z = (T[i] / Q[i][i]).sqrt(extend=False) L[i] = ( Z - U[i]).floor() x[i] = (-Z - U[i]).ceil() done_flag = False Q_val_double = RDF(0) Q_val = 0 ## WARNING: Still need a good way of checking overflow for this value... ## Big loop which runs through all vectors while not done_flag: ## 3b. Main loop -- try to generate a complete vector x (when i=0) while (i > 0): #print " i = ", i #print " T[i] = ", T[i] #print " Q[i][i] = ", Q[i][i] #print " x[i] = ", x[i] #print " U[i] = ", U[i] #print " x[i] + U[i] = ", (x[i] + U[i]) #print " T[i-1] = ", T[i-1] T[i-1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) #print " T[i-1] = ", T[i-1] #print " x = ", x #print i = i - 1 U[i] = 0 for j in range(i+1, n): U[i] = U[i] + Q[i][j] * x[j] ## Now go back and compute the bounds... ## 2. Compute bounds Z = (T[i] / Q[i][i]).sqrt(extend=False) L[i] = ( Z - U[i]).floor() x[i] = (-Z - U[i]).ceil() ## 4. Solution found (This happens when i = 0) #print "-- Solution found! --" #print " x = ", x #print " Q_val = Q(x) = ", Q_val Q_val_double = Theta_Precision - T[0] + Q[0][0] * (x[0] + U[0]) * (x[0] + U[0]) Q_val = ZZ(floor(round(Q_val_double))) ## SANITY CHECK: Roundoff Error is < 0.001 if abs(Q_val_double - Q_val) > 0.001: print " x = ", x print " Float = ", Q_val_double, " Long = ", Q_val raise RuntimeError, "The roundoff error is bigger than 0.001, so we should use more precision somewhere..." #print " Float = ", Q_val_double, " Long = ", Q_val, " XX " #print " The float value is ", Q_val_double #print " The associated long value is ", Q_val if (Q_val <= Theta_Precision): #print " Have vector ", x, " with value ", Q_val theta_vec[Q_val].append(deepcopy(x)) ## 5. Check if x = 0, for exit condition. =) j = 0 done_flag = True while (j < n): if (x[j] != 0): done_flag = False j += 1 ## 3a. Increment (and carry if we go out of bounds) x[i] += 1 while (x[i] > L[i]) and (i < n-1): i += 1 x[i] += 1 #print " Leaving ThetaVectors()" return theta_vec
| 473,200
|
def vectors_by_length(self, bound): """ Returns a list of short vectors together with their values. This is a naive algorithm which uses the Cholesky decomposition, but does not use the LLL-reduction algorithm. INPUT: bound -- an integer >= 0 OUTPUT: A list L of length (bound + 1) whose entry L[i] is a list of all vectors of length i. Reference: This is a slightly modified version of Cohn's Algorithm 2.7.5 in "A Course in Computational Number Theory", with the increment step moved around and slightly re-indexed to allow clean looping. Note: We could speed this up for very skew matrices by using LLL first, and then changing coordinates back, but for our purposes the simpler method is efficient enough. =) EXAMPLES: sage: Q = DiagonalQuadraticForm(ZZ, [1,1]) sage: Q.vectors_by_length(5) [[[0, 0]], [[0, -1], [-1, 0]], [[-1, -1], [1, -1]], [], [[0, -2], [-2, 0]], [[-1, -2], [1, -2], [-2, -1], [2, -1]]] sage: Q1 = DiagonalQuadraticForm(ZZ, [1,3,5,7]) sage: Q1.vectors_by_length(5) [[[0, 0, 0, 0]], [[-1, 0, 0, 0]], [], [[0, -1, 0, 0]], [[-1, -1, 0, 0], [1, -1, 0, 0], [-2, 0, 0, 0]], [[0, 0, -1, 0]]] """ Theta_Precision = bound ## Unsigned long n = self.dim() ## Make the vector of vectors which have a given value ## (So theta_vec[i] will have all vectors v with Q(v) = i.) empty_vec_list = [[] for i in range(Theta_Precision + 1)] theta_vec = [[] for i in range(Theta_Precision + 1)] ## Initialize Q with zeros and Copy the Cholesky array into Q Q = self.cholesky_decomposition() ## 1. Initialize T = n * [RDF(0)] ## Note: We index the entries as 0 --> n-1 U = n * [RDF(0)] i = n-1 T[i] = RDF(Theta_Precision) U[i] = RDF(0) L = n * [0] x = n * [0] Z = RDF(0) ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) done_flag = False Q_val_double = RDF(0) Q_val = 0 ## WARNING: Still need a good way of checking overflow for this value... ## Big loop which runs through all vectors while not done_flag: ## 3b. Main loop -- try to generate a complete vector x (when i=0) while (i > 0): #print " i = ", i #print " T[i] = ", T[i] #print " Q[i][i] = ", Q[i][i] #print " x[i] = ", x[i] #print " U[i] = ", U[i] #print " x[i] + U[i] = ", (x[i] + U[i]) #print " T[i-1] = ", T[i-1] T[i-1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) #print " T[i-1] = ", T[i-1] #print " x = ", x #print i = i - 1 U[i] = 0 for j in range(i+1, n): U[i] = U[i] + Q[i][j] * x[j] ## Now go back and compute the bounds... ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) ## 4. Solution found (This happens when i = 0) #print "-- Solution found! --" #print " x = ", x #print " Q_val = Q(x) = ", Q_val Q_val_double = Theta_Precision - T[0] + Q[0][0] * (x[0] + U[0]) * (x[0] + U[0]) Q_val = ZZ(floor(round(Q_val_double))) ## SANITY CHECK: Roundoff Error is < 0.001 if abs(Q_val_double - Q_val) > 0.001: print " x = ", x print " Float = ", Q_val_double, " Long = ", Q_val raise RuntimeError, "The roundoff error is bigger than 0.001, so we should use more precision somewhere..." #print " Float = ", Q_val_double, " Long = ", Q_val, " XX " #print " The float value is ", Q_val_double #print " The associated long value is ", Q_val if (Q_val <= Theta_Precision): #print " Have vector ", x, " with value ", Q_val theta_vec[Q_val].append(deepcopy(x)) ## 5. Check if x = 0, for exit condition. =) j = 0 done_flag = True while (j < n): if (x[j] != 0): done_flag = False j += 1 ## 3a. Increment (and carry if we go out of bounds) x[i] += 1 while (x[i] > L[i]) and (i < n-1): i += 1 x[i] += 1 #print " Leaving ThetaVectors()" return theta_vec
|
def vectors_by_length(self, bound): """ Returns a list of short vectors together with their values. This is a naive algorithm which uses the Cholesky decomposition, but does not use the LLL-reduction algorithm. INPUT: bound -- an integer >= 0 OUTPUT: A list L of length (bound + 1) whose entry L[i] is a list of all vectors of length i. Reference: This is a slightly modified version of Cohn's Algorithm 2.7.5 in "A Course in Computational Number Theory", with the increment step moved around and slightly re-indexed to allow clean looping. Note: We could speed this up for very skew matrices by using LLL first, and then changing coordinates back, but for our purposes the simpler method is efficient enough. =) EXAMPLES: sage: Q = DiagonalQuadraticForm(ZZ, [1,1]) sage: Q.vectors_by_length(5) [[[0, 0]], [[0, -1], [-1, 0]], [[-1, -1], [1, -1]], [], [[0, -2], [-2, 0]], [[-1, -2], [1, -2], [-2, -1], [2, -1]]] sage: Q1 = DiagonalQuadraticForm(ZZ, [1,3,5,7]) sage: Q1.vectors_by_length(5) [[[0, 0, 0, 0]], [[-1, 0, 0, 0]], [], [[0, -1, 0, 0]], [[-1, -1, 0, 0], [1, -1, 0, 0], [-2, 0, 0, 0]], [[0, 0, -1, 0]]] """ Theta_Precision = bound ## Unsigned long n = self.dim() ## Make the vector of vectors which have a given value ## (So theta_vec[i] will have all vectors v with Q(v) = i.) empty_vec_list = [[] for i in range(Theta_Precision + 1)] theta_vec = [[] for i in range(Theta_Precision + 1)] ## Initialize Q with zeros and Copy the Cholesky array into Q Q = self.cholesky_decomposition() ## 1. Initialize T = n * [RDF(0)] ## Note: We index the entries as 0 --> n-1 U = n * [RDF(0)] i = n-1 T[i] = RDF(Theta_Precision) U[i] = RDF(0) L = n * [0] x = n * [0] Z = RDF(0) ## 2. Compute bounds Z = (T[i] / Q[i][i]).sqrt(extend=False) L[i] = ( Z - U[i]).floor() x[i] = (-Z - U[i]).ceil() done_flag = False Q_val_double = RDF(0) Q_val = 0 ## WARNING: Still need a good way of checking overflow for this value... ## Big loop which runs through all vectors while not done_flag: ## 3b. Main loop -- try to generate a complete vector x (when i=0) while (i > 0): #print " i = ", i #print " T[i] = ", T[i] #print " Q[i][i] = ", Q[i][i] #print " x[i] = ", x[i] #print " U[i] = ", U[i] #print " x[i] + U[i] = ", (x[i] + U[i]) #print " T[i-1] = ", T[i-1] T[i-1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) #print " T[i-1] = ", T[i-1] #print " x = ", x #print i = i - 1 U[i] = 0 for j in range(i+1, n): U[i] = U[i] + Q[i][j] * x[j] ## Now go back and compute the bounds... ## 2. Compute bounds Z = (T[i] / Q[i][i]).sqrt(extend=False) L[i] = ( Z - U[i]).floor() x[i] = (-Z - U[i]).ceil() ## 4. Solution found (This happens when i = 0) #print "-- Solution found! --" #print " x = ", x #print " Q_val = Q(x) = ", Q_val Q_val_double = Theta_Precision - T[0] + Q[0][0] * (x[0] + U[0]) * (x[0] + U[0]) Q_val = ZZ(floor(round(Q_val_double))) ## SANITY CHECK: Roundoff Error is < 0.001 if abs(Q_val_double - Q_val) > 0.001: print " x = ", x print " Float = ", Q_val_double, " Long = ", Q_val raise RuntimeError, "The roundoff error is bigger than 0.001, so we should use more precision somewhere..." #print " Float = ", Q_val_double, " Long = ", Q_val, " XX " #print " The float value is ", Q_val_double #print " The associated long value is ", Q_val if (Q_val <= Theta_Precision): #print " Have vector ", x, " with value ", Q_val theta_vec[Q_val].append(deepcopy(x)) ## 5. Check if x = 0, for exit condition. =) j = 0 done_flag = True while (j < n): if (x[j] != 0): done_flag = False j += 1 ## 3a. Increment (and carry if we go out of bounds) x[i] += 1 while (x[i] > L[i]) and (i < n-1): i += 1 x[i] += 1 #print " Leaving ThetaVectors()" return theta_vec
| 473,201
|
def vectors_by_length(self, bound): """ Returns a list of short vectors together with their values. This is a naive algorithm which uses the Cholesky decomposition, but does not use the LLL-reduction algorithm. INPUT: bound -- an integer >= 0 OUTPUT: A list L of length (bound + 1) whose entry L[i] is a list of all vectors of length i. Reference: This is a slightly modified version of Cohn's Algorithm 2.7.5 in "A Course in Computational Number Theory", with the increment step moved around and slightly re-indexed to allow clean looping. Note: We could speed this up for very skew matrices by using LLL first, and then changing coordinates back, but for our purposes the simpler method is efficient enough. =) EXAMPLES: sage: Q = DiagonalQuadraticForm(ZZ, [1,1]) sage: Q.vectors_by_length(5) [[[0, 0]], [[0, -1], [-1, 0]], [[-1, -1], [1, -1]], [], [[0, -2], [-2, 0]], [[-1, -2], [1, -2], [-2, -1], [2, -1]]] sage: Q1 = DiagonalQuadraticForm(ZZ, [1,3,5,7]) sage: Q1.vectors_by_length(5) [[[0, 0, 0, 0]], [[-1, 0, 0, 0]], [], [[0, -1, 0, 0]], [[-1, -1, 0, 0], [1, -1, 0, 0], [-2, 0, 0, 0]], [[0, 0, -1, 0]]] """ Theta_Precision = bound ## Unsigned long n = self.dim() ## Make the vector of vectors which have a given value ## (So theta_vec[i] will have all vectors v with Q(v) = i.) empty_vec_list = [[] for i in range(Theta_Precision + 1)] theta_vec = [[] for i in range(Theta_Precision + 1)] ## Initialize Q with zeros and Copy the Cholesky array into Q Q = self.cholesky_decomposition() ## 1. Initialize T = n * [RDF(0)] ## Note: We index the entries as 0 --> n-1 U = n * [RDF(0)] i = n-1 T[i] = RDF(Theta_Precision) U[i] = RDF(0) L = n * [0] x = n * [0] Z = RDF(0) ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) done_flag = False Q_val_double = RDF(0) Q_val = 0 ## WARNING: Still need a good way of checking overflow for this value... ## Big loop which runs through all vectors while not done_flag: ## 3b. Main loop -- try to generate a complete vector x (when i=0) while (i > 0): #print " i = ", i #print " T[i] = ", T[i] #print " Q[i][i] = ", Q[i][i] #print " x[i] = ", x[i] #print " U[i] = ", U[i] #print " x[i] + U[i] = ", (x[i] + U[i]) #print " T[i-1] = ", T[i-1] T[i-1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) #print " T[i-1] = ", T[i-1] #print " x = ", x #print i = i - 1 U[i] = 0 for j in range(i+1, n): U[i] = U[i] + Q[i][j] * x[j] ## Now go back and compute the bounds... ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) ## 4. Solution found (This happens when i = 0) #print "-- Solution found! --" #print " x = ", x #print " Q_val = Q(x) = ", Q_val Q_val_double = Theta_Precision - T[0] + Q[0][0] * (x[0] + U[0]) * (x[0] + U[0]) Q_val = ZZ(floor(round(Q_val_double))) ## SANITY CHECK: Roundoff Error is < 0.001 if abs(Q_val_double - Q_val) > 0.001: print " x = ", x print " Float = ", Q_val_double, " Long = ", Q_val raise RuntimeError, "The roundoff error is bigger than 0.001, so we should use more precision somewhere..." #print " Float = ", Q_val_double, " Long = ", Q_val, " XX " #print " The float value is ", Q_val_double #print " The associated long value is ", Q_val if (Q_val <= Theta_Precision): #print " Have vector ", x, " with value ", Q_val theta_vec[Q_val].append(deepcopy(x)) ## 5. Check if x = 0, for exit condition. =) j = 0 done_flag = True while (j < n): if (x[j] != 0): done_flag = False j += 1 ## 3a. Increment (and carry if we go out of bounds) x[i] += 1 while (x[i] > L[i]) and (i < n-1): i += 1 x[i] += 1 #print " Leaving ThetaVectors()" return theta_vec
|
def vectors_by_length(self, bound): """ Returns a list of short vectors together with their values. This is a naive algorithm which uses the Cholesky decomposition, but does not use the LLL-reduction algorithm. INPUT: bound -- an integer >= 0 OUTPUT: A list L of length (bound + 1) whose entry L[i] is a list of all vectors of length i. Reference: This is a slightly modified version of Cohn's Algorithm 2.7.5 in "A Course in Computational Number Theory", with the increment step moved around and slightly re-indexed to allow clean looping. Note: We could speed this up for very skew matrices by using LLL first, and then changing coordinates back, but for our purposes the simpler method is efficient enough. =) EXAMPLES: sage: Q = DiagonalQuadraticForm(ZZ, [1,1]) sage: Q.vectors_by_length(5) [[[0, 0]], [[0, -1], [-1, 0]], [[-1, -1], [1, -1]], [], [[0, -2], [-2, 0]], [[-1, -2], [1, -2], [-2, -1], [2, -1]]] sage: Q1 = DiagonalQuadraticForm(ZZ, [1,3,5,7]) sage: Q1.vectors_by_length(5) [[[0, 0, 0, 0]], [[-1, 0, 0, 0]], [], [[0, -1, 0, 0]], [[-1, -1, 0, 0], [1, -1, 0, 0], [-2, 0, 0, 0]], [[0, 0, -1, 0]]] """ Theta_Precision = bound ## Unsigned long n = self.dim() ## Make the vector of vectors which have a given value ## (So theta_vec[i] will have all vectors v with Q(v) = i.) empty_vec_list = [[] for i in range(Theta_Precision + 1)] theta_vec = [[] for i in range(Theta_Precision + 1)] ## Initialize Q with zeros and Copy the Cholesky array into Q Q = self.cholesky_decomposition() ## 1. Initialize T = n * [RDF(0)] ## Note: We index the entries as 0 --> n-1 U = n * [RDF(0)] i = n-1 T[i] = RDF(Theta_Precision) U[i] = RDF(0) L = n * [0] x = n * [0] Z = RDF(0) ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) done_flag = False Q_val_double = RDF(0) Q_val = 0 ## WARNING: Still need a good way of checking overflow for this value... ## Big loop which runs through all vectors while not done_flag: ## 3b. Main loop -- try to generate a complete vector x (when i=0) while (i > 0): #print " i = ", i #print " T[i] = ", T[i] #print " Q[i][i] = ", Q[i][i] #print " x[i] = ", x[i] #print " U[i] = ", U[i] #print " x[i] + U[i] = ", (x[i] + U[i]) #print " T[i-1] = ", T[i-1] T[i-1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) #print " T[i-1] = ", T[i-1] #print " x = ", x #print i = i - 1 U[i] = 0 for j in range(i+1, n): U[i] = U[i] + Q[i][j] * x[j] ## Now go back and compute the bounds... ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) ## 4. Solution found (This happens when i = 0) #print "-- Solution found! --" #print " x = ", x #print " Q_val = Q(x) = ", Q_val Q_val_double = Theta_Precision - T[0] + Q[0][0] * (x[0] + U[0]) * (x[0] + U[0]) Q_val = Q_val_double.round() ## SANITY CHECK: Roundoff Error is < 0.001 if abs(Q_val_double - Q_val) > 0.001: print " x = ", x print " Float = ", Q_val_double, " Long = ", Q_val raise RuntimeError, "The roundoff error is bigger than 0.001, so we should use more precision somewhere..." #print " Float = ", Q_val_double, " Long = ", Q_val, " XX " #print " The float value is ", Q_val_double #print " The associated long value is ", Q_val if (Q_val <= Theta_Precision): #print " Have vector ", x, " with value ", Q_val theta_vec[Q_val].append(deepcopy(x)) ## 5. Check if x = 0, for exit condition. =) j = 0 done_flag = True while (j < n): if (x[j] != 0): done_flag = False j += 1 ## 3a. Increment (and carry if we go out of bounds) x[i] += 1 while (x[i] > L[i]) and (i < n-1): i += 1 x[i] += 1 #print " Leaving ThetaVectors()" return theta_vec
| 473,202
|
def vectors_by_length(self, bound): """ Returns a list of short vectors together with their values. This is a naive algorithm which uses the Cholesky decomposition, but does not use the LLL-reduction algorithm. INPUT: bound -- an integer >= 0 OUTPUT: A list L of length (bound + 1) whose entry L[i] is a list of all vectors of length i. Reference: This is a slightly modified version of Cohn's Algorithm 2.7.5 in "A Course in Computational Number Theory", with the increment step moved around and slightly re-indexed to allow clean looping. Note: We could speed this up for very skew matrices by using LLL first, and then changing coordinates back, but for our purposes the simpler method is efficient enough. =) EXAMPLES: sage: Q = DiagonalQuadraticForm(ZZ, [1,1]) sage: Q.vectors_by_length(5) [[[0, 0]], [[0, -1], [-1, 0]], [[-1, -1], [1, -1]], [], [[0, -2], [-2, 0]], [[-1, -2], [1, -2], [-2, -1], [2, -1]]] sage: Q1 = DiagonalQuadraticForm(ZZ, [1,3,5,7]) sage: Q1.vectors_by_length(5) [[[0, 0, 0, 0]], [[-1, 0, 0, 0]], [], [[0, -1, 0, 0]], [[-1, -1, 0, 0], [1, -1, 0, 0], [-2, 0, 0, 0]], [[0, 0, -1, 0]]] """ Theta_Precision = bound ## Unsigned long n = self.dim() ## Make the vector of vectors which have a given value ## (So theta_vec[i] will have all vectors v with Q(v) = i.) empty_vec_list = [[] for i in range(Theta_Precision + 1)] theta_vec = [[] for i in range(Theta_Precision + 1)] ## Initialize Q with zeros and Copy the Cholesky array into Q Q = self.cholesky_decomposition() ## 1. Initialize T = n * [RDF(0)] ## Note: We index the entries as 0 --> n-1 U = n * [RDF(0)] i = n-1 T[i] = RDF(Theta_Precision) U[i] = RDF(0) L = n * [0] x = n * [0] Z = RDF(0) ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) done_flag = False Q_val_double = RDF(0) Q_val = 0 ## WARNING: Still need a good way of checking overflow for this value... ## Big loop which runs through all vectors while not done_flag: ## 3b. Main loop -- try to generate a complete vector x (when i=0) while (i > 0): #print " i = ", i #print " T[i] = ", T[i] #print " Q[i][i] = ", Q[i][i] #print " x[i] = ", x[i] #print " U[i] = ", U[i] #print " x[i] + U[i] = ", (x[i] + U[i]) #print " T[i-1] = ", T[i-1] T[i-1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) #print " T[i-1] = ", T[i-1] #print " x = ", x #print i = i - 1 U[i] = 0 for j in range(i+1, n): U[i] = U[i] + Q[i][j] * x[j] ## Now go back and compute the bounds... ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) ## 4. Solution found (This happens when i = 0) #print "-- Solution found! --" #print " x = ", x #print " Q_val = Q(x) = ", Q_val Q_val_double = Theta_Precision - T[0] + Q[0][0] * (x[0] + U[0]) * (x[0] + U[0]) Q_val = ZZ(floor(round(Q_val_double))) ## SANITY CHECK: Roundoff Error is < 0.001 if abs(Q_val_double - Q_val) > 0.001: print " x = ", x print " Float = ", Q_val_double, " Long = ", Q_val raise RuntimeError, "The roundoff error is bigger than 0.001, so we should use more precision somewhere..." #print " Float = ", Q_val_double, " Long = ", Q_val, " XX " #print " The float value is ", Q_val_double #print " The associated long value is ", Q_val if (Q_val <= Theta_Precision): #print " Have vector ", x, " with value ", Q_val theta_vec[Q_val].append(deepcopy(x)) ## 5. Check if x = 0, for exit condition. =) j = 0 done_flag = True while (j < n): if (x[j] != 0): done_flag = False j += 1 ## 3a. Increment (and carry if we go out of bounds) x[i] += 1 while (x[i] > L[i]) and (i < n-1): i += 1 x[i] += 1 #print " Leaving ThetaVectors()" return theta_vec
|
def vectors_by_length(self, bound): """ Returns a list of short vectors together with their values. This is a naive algorithm which uses the Cholesky decomposition, but does not use the LLL-reduction algorithm. INPUT: bound -- an integer >= 0 OUTPUT: A list L of length (bound + 1) whose entry L[i] is a list of all vectors of length i. Reference: This is a slightly modified version of Cohn's Algorithm 2.7.5 in "A Course in Computational Number Theory", with the increment step moved around and slightly re-indexed to allow clean looping. Note: We could speed this up for very skew matrices by using LLL first, and then changing coordinates back, but for our purposes the simpler method is efficient enough. =) EXAMPLES: sage: Q = DiagonalQuadraticForm(ZZ, [1,1]) sage: Q.vectors_by_length(5) [[[0, 0]], [[0, -1], [-1, 0]], [[-1, -1], [1, -1]], [], [[0, -2], [-2, 0]], [[-1, -2], [1, -2], [-2, -1], [2, -1]]] sage: Q1 = DiagonalQuadraticForm(ZZ, [1,3,5,7]) sage: Q1.vectors_by_length(5) [[[0, 0, 0, 0]], [[-1, 0, 0, 0]], [], [[0, -1, 0, 0]], [[-1, -1, 0, 0], [1, -1, 0, 0], [-2, 0, 0, 0]], [[0, 0, -1, 0]]] """ Theta_Precision = bound ## Unsigned long n = self.dim() ## Make the vector of vectors which have a given value ## (So theta_vec[i] will have all vectors v with Q(v) = i.) empty_vec_list = [[] for i in range(Theta_Precision + 1)] theta_vec = [[] for i in range(Theta_Precision + 1)] ## Initialize Q with zeros and Copy the Cholesky array into Q Q = self.cholesky_decomposition() ## 1. Initialize T = n * [RDF(0)] ## Note: We index the entries as 0 --> n-1 U = n * [RDF(0)] i = n-1 T[i] = RDF(Theta_Precision) U[i] = RDF(0) L = n * [0] x = n * [0] Z = RDF(0) ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) done_flag = False Q_val_double = RDF(0) Q_val = 0 ## WARNING: Still need a good way of checking overflow for this value... ## Big loop which runs through all vectors while not done_flag: ## 3b. Main loop -- try to generate a complete vector x (when i=0) while (i > 0): #print " i = ", i #print " T[i] = ", T[i] #print " Q[i][i] = ", Q[i][i] #print " x[i] = ", x[i] #print " U[i] = ", U[i] #print " x[i] + U[i] = ", (x[i] + U[i]) #print " T[i-1] = ", T[i-1] T[i-1] = T[i] - Q[i][i] * (x[i] + U[i]) * (x[i] + U[i]) #print " T[i-1] = ", T[i-1] #print " x = ", x #print i = i - 1 U[i] = 0 for j in range(i+1, n): U[i] = U[i] + Q[i][j] * x[j] ## Now go back and compute the bounds... ## 2. Compute bounds Z = sqrt(T[i] / Q[i][i]) L[i] = ZZ(floor(Z - U[i])) x[i] = ZZ(ceil(-Z - U[i]) - 0) ## 4. Solution found (This happens when i = 0) #print "-- Solution found! --" #print " x = ", x #print " Q_val = Q(x) = ", Q_val Q_val_double = Theta_Precision - T[0] + Q[0][0] * (x[0] + U[0]) * (x[0] + U[0]) Q_val = ZZ(floor(round(Q_val_double))) ## SANITY CHECK: Roundoff Error is < 0.001 if abs(Q_val_double - Q_val) > 0.001: print " x = ", x print " Float = ", Q_val_double, " Long = ", Q_val raise RuntimeError, "The roundoff error is bigger than 0.001, so we should use more precision somewhere..." #print " Float = ", Q_val_double, " Long = ", Q_val, " XX " #print " The float value is ", Q_val_double #print " The associated long value is ", Q_val if (Q_val <= bound): #print " Have vector ", x, " with value ", Q_val theta_vec[Q_val].append(deepcopy(x)) ## 5. Check if x = 0, for exit condition. =) j = 0 done_flag = True while (j < n): if (x[j] != 0): done_flag = False j += 1 ## 3a. Increment (and carry if we go out of bounds) x[i] += 1 while (x[i] > L[i]) and (i < n-1): i += 1 x[i] += 1 #print " Leaving ThetaVectors()" return theta_vec
| 473,203
|
... def __repr__(self):
|
... def __repr__(self):
| 473,204
|
... def __repr__(self):
|
... def __repr__(self):
| 473,205
|
... def __repr__(self):
|
... def __repr__(self):
| 473,206
|
... def __repr__(self):
|
... def __repr__(self):
| 473,207
|
... def __repr__(self):
|
... def __repr__(self):
| 473,208
|
... def __repr__(self):
|
... def __repr__(self):
| 473,209
|
def __mod__(self, args): """ Binds the lazy format with its parameters
|
def __mod__(self, args): """ Binds the lazy format with its parameters
| 473,210
|
def simon_two_descent(self, verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Computes lower and upper bounds on the rank of the Mordell-Weil group, and a list of independent points.
|
def simon_two_descent(self, verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Computes lower and upper bounds on the rank of the Mordell-Weil group, and a list of independent points.
| 473,211
|
def simon_two_descent(self, verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Computes lower and upper bounds on the rank of the Mordell-Weil group, and a list of independent points.
|
def simon_two_descent(self, verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Computes lower and upper bounds on the rank of the Mordell-Weil group, and a list of independent points.
| 473,212
|
def rank_bounds(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Returns the lower and upper bounds using simon_two_descent. The results of simon_two_descent are cached.
|
def rank_bounds(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Returns the lower and upper bounds using simon_two_descent. The results of simon_two_descent are cached.
| 473,213
|
def rank_bounds(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Returns the lower and upper bounds using simon_two_descent. The results of simon_two_descent are cached.
|
def rank_bounds(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Returns the lower and upper bounds using simon_two_descent. The results of simon_two_descent are cached.
| 473,214
|
def rank_bounds(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Returns the lower and upper bounds using simon_two_descent. The results of simon_two_descent are cached.
|
def rank_bounds(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Returns the lower and upper bounds using simon_two_descent. The results of simon_two_descent are cached.
| 473,215
|
def rank(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Return the rank of this elliptic curve, if it can be determined.
|
def rank(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Return the rank of this elliptic curve, if it can be determined.
| 473,216
|
def rank(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Return the rank of this elliptic curve, if it can be determined.
|
def rank(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Return the rank of this elliptic curve, if it can be determined.
| 473,217
|
def rank(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Return the rank of this elliptic curve, if it can be determined.
|
def rank(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Return the rank of this elliptic curve, if it can be determined.
| 473,218
|
def rank(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Return the rank of this elliptic curve, if it can be determined.
|
def rank(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Return the rank of this elliptic curve, if it can be determined.
| 473,219
|
def rank(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Return the rank of this elliptic curve, if it can be determined.
|
def rank(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Return the rank of this elliptic curve, if it can be determined.
| 473,220
|
def rank(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Return the rank of this elliptic curve, if it can be determined.
|
def rank(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Return the rank of this elliptic curve, if it can be determined.
| 473,221
|
def gens(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Returns some generators of this elliptic curve. Check rank or rank_bound to verify the number of generators.
|
def gens(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Returns some generators of this elliptic curve. Check rank or rank_bound to verify the number of generators.
| 473,222
|
def gens(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Returns some generators of this elliptic curve. Check rank or rank_bound to verify the number of generators.
|
def gens(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Returns some generators of this elliptic curve. Check rank or rank_bound to verify the number of generators.
| 473,223
|
def gens(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Returns some generators of this elliptic curve. Check rank or rank_bound to verify the number of generators.
|
def gens(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Returns some generators of this elliptic curve. Check rank or rank_bound to verify the number of generators.
| 473,224
|
def gens(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Returns some generators of this elliptic curve. Check rank or rank_bound to verify the number of generators.
|
def gens(self,verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Returns some generators of this elliptic curve. Check rank or rank_bound to verify the number of generators.
| 473,225
|
def __call__(self, im_gens, check=True): """ Return the homomorphism defined by images of generators.
|
def __call__(self, im_gens, check=True): """ Return the homomorphism defined by images of generators.
| 473,226
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
| 473,227
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
| 473,228
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
|
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
| 473,229
|
def str_to_unit(name): """ Create the symbolic unit with given name. A symbolic unit is a class that derives from symbolic expression, and has a specialized docstring. INPUT: - ``name`` -- string OUTPUT: - UnitExpression EXAMPLES:: sage: sage.symbolic.units.str_to_unit('acre') acre sage: type(sage.symbolic.units.str_to_unit('acre')) <class 'sage.symbolic.units.UnitExpression'> """ return UnitExpression(SR, SR.var(name))
|
def str_to_unit(name): """ Create the symbolic unit with given name. A symbolic unit is a class that derives from symbolic expression, and has a specialized docstring. INPUT: - ``name`` -- string OUTPUT: - UnitExpression EXAMPLES:: sage: sage.symbolic.units.str_to_unit('acre') acre sage: type(sage.symbolic.units.str_to_unit('acre')) <class 'sage.symbolic.units.UnitExpression'> """ return UnitExpression(SR, SR.var(name))
| 473,230
|
def __init__(self, data, name=''): """ EXAMPLES::
|
def __init__(self, data, name=''): """ EXAMPLES::
| 473,231
|
def __getattr__(self, name): """ Return the unit with the given name.
|
def __getattr__(self, name): """ Return the unit with the given name.
| 473,232
|
def __repr__(self): """ Return string representation of this collection of units.
|
def __repr__(self): """ Return string representation of this collection of units.
| 473,233
|
def solve(f, *args, **kwds): r""" Algebraically solve an equation or system of equations (over the complex numbers) for given variables. Inequalities and systems of inequalities are also supported. INPUT: - ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict`` - bool (default: False); if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: x, y = var('x, y') sage: solve([x+y==6, x-y==4], x, y) [[x == 5, y == 1]] sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y) [[x == -1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == -1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 0, y == -1], [x == 0, y == 1]] sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y) [[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]] sage: solutions=solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True) sage: for solution in solutions: print solution[x].n(digits=3), ",", solution[y].n(digits=3) -0.500 - 0.866*I , -1.27 + 0.341*I -0.500 - 0.866*I , 1.27 - 0.341*I -0.500 + 0.866*I , -1.27 - 0.341*I -0.500 + 0.866*I , 1.27 + 0.341*I 0.000 , -1.00 0.000 , 1.00 Whenever possible, answers will be symbolic, but with systems of equations, at times approximations will be given, due to the underlying algorithm in Maxima:: sage: sols = solve([x^3==y,y^2==x],[x,y]); sols[-1], sols[0] ([x == 0, y == 0], [x == (0.309016994375 + 0.951056516295*I), y == (-0.809016994375 - 0.587785252292*I)]) sage: sols[0][0].rhs().pyobject().parent() Complex Double Field If ``f`` is only one equation or expression, we use the solve method for symbolic expressions, which defaults to exact answers only:: sage: solve([y^6==y],y) [y == e^(2/5*I*pi), y == e^(4/5*I*pi), y == e^(-4/5*I*pi), y == e^(-2/5*I*pi), y == 1, y == 0] sage: solve( [y^6 == y], y)==solve( y^6 == y, y) True .. note:: For more details about solving a single equations, see the documentation for its solve. :: sage: from sage.symbolic.expression import Expression sage: Expression.solve(x^2==1,x) [x == -1, x == 1] We must solve with respect to actual variables:: sage: z = 5 sage: solve([8*z + y == 3, -z +7*y == 0],y,z) Traceback (most recent call last): ... TypeError: 5 is not a valid variable. If we ask for a dictionary for the solutions, we get it:: sage: solve([x^2-1],x,solution_dict=True) [{x: -1}, {x: 1}] sage: solve([x^2-4*x+4],x,solution_dict=True) [{x: 2}] sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True) sage: for soln in res: print "x: %s, y: %s"%(soln[x], soln[y]) x: 2, y: 4 x: -2, y: 4 If there is a parameter in the answer, that will show up as a new variable. In the following example, ``r1`` is a real free variable (because of the ``r``):: sage: solve([x+y == 3, 2*x+2*y == 6],x,y) [[x == -r1 + 3, y == r1]] Especially with trigonometric functions, the dummy variable may be implicitly an integer (hence the ``z``):: sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y) [[x == 1/4*pi + pi*z38, y == -1/4*pi - pi*z38]] Expressions which are not equations are assumed to be set equal to zero, as with `x` in the following example:: sage: solve([x, y == 2],x,y) [[x == 0, y == 2]] If ``True`` appears in the list of equations it is ignored, and if ``False`` appears in the list then no solutions are returned. E.g., note that the first ``3==3`` evaluates to ``True``, not to a symbolic equation. :: sage: solve([3==3, 1.00000000000000*x^3 == 0], x) [x == 0] sage: solve([1.00000000000000*x^3 == 0], x) [x == 0] Here, the first equation evaluates to ``False``, so there are no solutions:: sage: solve([1==3, 1.00000000000000*x^3 == 0], x) [] Completely symbolic solutions are supported:: sage: var('s,j,b,m,g') (s, j, b, m, g) sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ]; sage: solve(sys,s,j) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,(s,j)) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,[s,j]) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] Inequalities can be also solved:: sage: solve(x^2>8,x) [[x < -2*sqrt(2)], [x > 2*sqrt(2)]] TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x] Use use_grobner if no solution is obtained from to_poly_solve:: sage: x,y=var('x y'); c1(x,y)=(x-5)^2+y^2-16; c2(x,y)=(y-3)^2+x^2-9 sage: solve([c1(x,y),c2(x,y)],[x,y]) [[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(5)*sqrt(11) + 123/68], [x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(5)*sqrt(11) + 123/68]] """ from sage.symbolic.expression import is_Expression if is_Expression(f): # f is a single expression ans = f.solve(*args,**kwds) return ans elif len(f)==1 and is_Expression(f[0]): # f is a list with a single expression ans = f[0].solve(*args,**kwds) return ans else: # f is a list of such expressions or equations from sage.symbolic.ring import is_SymbolicVariable if len(args)==0: raise TypeError, "Please input variables to solve for." if is_SymbolicVariable(args[0]): variables = args else: variables = tuple(args[0]) for v in variables: if not is_SymbolicVariable(v): raise TypeError, "%s is not a valid variable."%v try: f = [s for s in f if s is not True] except TypeError: raise ValueError, "Unable to solve %s for %s"%(f, args) if any(s is False for s in f): return [] from sage.calculus.calculus import maxima m = maxima(f) try: s = m.solve(variables) except: # if Maxima gave an error, try its to_poly_solve try: s = m.to_poly_solve(variables) except TypeError, mess: # if that gives an error, raise an error. if "Error executing code in Maxima" in str(mess): raise ValueError, "Sage is unable to determine whether the system %s can be solved for %s"%(f,args) else: raise if len(s)==0: # if Maxima's solve gave no solutions, try its to_poly_solve try: s = m.to_poly_solve(variables) except: # if that gives an error, stick with no solutions s = [] if len(s)==0: # if to_poly_solve gave no solutions, try use_grobner try: s = m.to_poly_solve(variables,'use_grobner=true') except: # if that gives an error, stick with no solutions s = [] sol_list = string_to_list_of_solutions(repr(s)) if 'solution_dict' in kwds and kwds['solution_dict']==True: if isinstance(sol_list[0], list): sol_dict=[dict([[eq.left(),eq.right()] for eq in solution]) for solution in sol_list] else: sol_dict=[{eq.left():eq.right()} for eq in sol_list] return sol_dict else: return sol_list
|
def solve(f, *args, **kwds): r""" Algebraically solve an equation or system of equations (over the complex numbers) for given variables. Inequalities and systems of inequalities are also supported. INPUT: - ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict`` - bool (default: False); if True or non-zero, return a list of dictionaries containing the solutions. If there are no solutions, return an empty list (rather than a list containing an empty dictionary). Likewise, if there's only a single solution, return a list containing one dictionary with that solution. EXAMPLES:: sage: x, y = var('x, y') sage: solve([x+y==6, x-y==4], x, y) [[x == 5, y == 1]] sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y) [[x == -1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == -1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 0, y == -1], [x == 0, y == 1]] sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y) [[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]] sage: solutions=solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True) sage: for solution in solutions: print solution[x].n(digits=3), ",", solution[y].n(digits=3) -0.500 - 0.866*I , -1.27 + 0.341*I -0.500 - 0.866*I , 1.27 - 0.341*I -0.500 + 0.866*I , -1.27 - 0.341*I -0.500 + 0.866*I , 1.27 + 0.341*I 0.000 , -1.00 0.000 , 1.00 Whenever possible, answers will be symbolic, but with systems of equations, at times approximations will be given, due to the underlying algorithm in Maxima:: sage: sols = solve([x^3==y,y^2==x],[x,y]); sols[-1], sols[0] ([x == 0, y == 0], [x == (0.309016994375 + 0.951056516295*I), y == (-0.809016994375 - 0.587785252292*I)]) sage: sols[0][0].rhs().pyobject().parent() Complex Double Field If ``f`` is only one equation or expression, we use the solve method for symbolic expressions, which defaults to exact answers only:: sage: solve([y^6==y],y) [y == e^(2/5*I*pi), y == e^(4/5*I*pi), y == e^(-4/5*I*pi), y == e^(-2/5*I*pi), y == 1, y == 0] sage: solve( [y^6 == y], y)==solve( y^6 == y, y) True .. note:: For more details about solving a single equations, see the documentation for its solve. :: sage: from sage.symbolic.expression import Expression sage: Expression.solve(x^2==1,x) [x == -1, x == 1] We must solve with respect to actual variables:: sage: z = 5 sage: solve([8*z + y == 3, -z +7*y == 0],y,z) Traceback (most recent call last): ... TypeError: 5 is not a valid variable. If we ask for a dictionary for the solutions, we get it:: sage: solve([x^2-1],x,solution_dict=True) [{x: -1}, {x: 1}] sage: solve([x^2-4*x+4],x,solution_dict=True) [{x: 2}] sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True) sage: for soln in res: print "x: %s, y: %s"%(soln[x], soln[y]) x: 2, y: 4 x: -2, y: 4 If there is a parameter in the answer, that will show up as a new variable. In the following example, ``r1`` is a real free variable (because of the ``r``):: sage: solve([x+y == 3, 2*x+2*y == 6],x,y) [[x == -r1 + 3, y == r1]] Especially with trigonometric functions, the dummy variable may be implicitly an integer (hence the ``z``):: sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y) [[x == 1/4*pi + pi*z38, y == -1/4*pi - pi*z38]] Expressions which are not equations are assumed to be set equal to zero, as with `x` in the following example:: sage: solve([x, y == 2],x,y) [[x == 0, y == 2]] If ``True`` appears in the list of equations it is ignored, and if ``False`` appears in the list then no solutions are returned. E.g., note that the first ``3==3`` evaluates to ``True``, not to a symbolic equation. :: sage: solve([3==3, 1.00000000000000*x^3 == 0], x) [x == 0] sage: solve([1.00000000000000*x^3 == 0], x) [x == 0] Here, the first equation evaluates to ``False``, so there are no solutions:: sage: solve([1==3, 1.00000000000000*x^3 == 0], x) [] Completely symbolic solutions are supported:: sage: var('s,j,b,m,g') (s, j, b, m, g) sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ]; sage: solve(sys,s,j) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,(s,j)) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,[s,j]) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] Inequalities can be also solved:: sage: solve(x^2>8,x) [[x < -2*sqrt(2)], [x > 2*sqrt(2)]] TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x] Use use_grobner if no solution is obtained from to_poly_solve:: sage: x,y=var('x y'); c1(x,y)=(x-5)^2+y^2-16; c2(x,y)=(y-3)^2+x^2-9 sage: solve([c1(x,y),c2(x,y)],[x,y]) [[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(5)*sqrt(11) + 123/68], [x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(5)*sqrt(11) + 123/68]] """ from sage.symbolic.expression import is_Expression if is_Expression(f): # f is a single expression ans = f.solve(*args,**kwds) return ans elif len(f)==1 and is_Expression(f[0]): # f is a list with a single expression ans = f[0].solve(*args,**kwds) return ans else: # f is a list of such expressions or equations from sage.symbolic.ring import is_SymbolicVariable if len(args)==0: raise TypeError, "Please input variables to solve for." if is_SymbolicVariable(args[0]): variables = args else: variables = tuple(args[0]) for v in variables: if not is_SymbolicVariable(v): raise TypeError, "%s is not a valid variable."%v try: f = [s for s in f if s is not True] except TypeError: raise ValueError, "Unable to solve %s for %s"%(f, args) if any(s is False for s in f): return [] from sage.calculus.calculus import maxima m = maxima(f) try: s = m.solve(variables) except: # if Maxima gave an error, try its to_poly_solve try: s = m.to_poly_solve(variables) except TypeError, mess: # if that gives an error, raise an error. if "Error executing code in Maxima" in str(mess): raise ValueError, "Sage is unable to determine whether the system %s can be solved for %s"%(f,args) else: raise if len(s)==0: # if Maxima's solve gave no solutions, try its to_poly_solve try: s = m.to_poly_solve(variables) except: # if that gives an error, stick with no solutions s = [] if len(s)==0: # if to_poly_solve gave no solutions, try use_grobner try: s = m.to_poly_solve(variables,'use_grobner=true') except: # if that gives an error, stick with no solutions s = [] sol_list = string_to_list_of_solutions(repr(s)) if 'solution_dict' in kwds and kwds['solution_dict']==True: if isinstance(sol_list[0], list): sol_dict=[dict([[eq.left(),eq.right()] for eq in solution]) for solution in sol_list] else: sol_dict=[{eq.left():eq.right()} for eq in sol_list] return sol_dict else: return sol_list
| 473,234
|
def solve(f, *args, **kwds): r""" Algebraically solve an equation or system of equations (over the complex numbers) for given variables. Inequalities and systems of inequalities are also supported. INPUT: - ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict`` - bool (default: False); if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: x, y = var('x, y') sage: solve([x+y==6, x-y==4], x, y) [[x == 5, y == 1]] sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y) [[x == -1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == -1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 0, y == -1], [x == 0, y == 1]] sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y) [[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]] sage: solutions=solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True) sage: for solution in solutions: print solution[x].n(digits=3), ",", solution[y].n(digits=3) -0.500 - 0.866*I , -1.27 + 0.341*I -0.500 - 0.866*I , 1.27 - 0.341*I -0.500 + 0.866*I , -1.27 - 0.341*I -0.500 + 0.866*I , 1.27 + 0.341*I 0.000 , -1.00 0.000 , 1.00 Whenever possible, answers will be symbolic, but with systems of equations, at times approximations will be given, due to the underlying algorithm in Maxima:: sage: sols = solve([x^3==y,y^2==x],[x,y]); sols[-1], sols[0] ([x == 0, y == 0], [x == (0.309016994375 + 0.951056516295*I), y == (-0.809016994375 - 0.587785252292*I)]) sage: sols[0][0].rhs().pyobject().parent() Complex Double Field If ``f`` is only one equation or expression, we use the solve method for symbolic expressions, which defaults to exact answers only:: sage: solve([y^6==y],y) [y == e^(2/5*I*pi), y == e^(4/5*I*pi), y == e^(-4/5*I*pi), y == e^(-2/5*I*pi), y == 1, y == 0] sage: solve( [y^6 == y], y)==solve( y^6 == y, y) True .. note:: For more details about solving a single equations, see the documentation for its solve. :: sage: from sage.symbolic.expression import Expression sage: Expression.solve(x^2==1,x) [x == -1, x == 1] We must solve with respect to actual variables:: sage: z = 5 sage: solve([8*z + y == 3, -z +7*y == 0],y,z) Traceback (most recent call last): ... TypeError: 5 is not a valid variable. If we ask for a dictionary for the solutions, we get it:: sage: solve([x^2-1],x,solution_dict=True) [{x: -1}, {x: 1}] sage: solve([x^2-4*x+4],x,solution_dict=True) [{x: 2}] sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True) sage: for soln in res: print "x: %s, y: %s"%(soln[x], soln[y]) x: 2, y: 4 x: -2, y: 4 If there is a parameter in the answer, that will show up as a new variable. In the following example, ``r1`` is a real free variable (because of the ``r``):: sage: solve([x+y == 3, 2*x+2*y == 6],x,y) [[x == -r1 + 3, y == r1]] Especially with trigonometric functions, the dummy variable may be implicitly an integer (hence the ``z``):: sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y) [[x == 1/4*pi + pi*z38, y == -1/4*pi - pi*z38]] Expressions which are not equations are assumed to be set equal to zero, as with `x` in the following example:: sage: solve([x, y == 2],x,y) [[x == 0, y == 2]] If ``True`` appears in the list of equations it is ignored, and if ``False`` appears in the list then no solutions are returned. E.g., note that the first ``3==3`` evaluates to ``True``, not to a symbolic equation. :: sage: solve([3==3, 1.00000000000000*x^3 == 0], x) [x == 0] sage: solve([1.00000000000000*x^3 == 0], x) [x == 0] Here, the first equation evaluates to ``False``, so there are no solutions:: sage: solve([1==3, 1.00000000000000*x^3 == 0], x) [] Completely symbolic solutions are supported:: sage: var('s,j,b,m,g') (s, j, b, m, g) sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ]; sage: solve(sys,s,j) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,(s,j)) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,[s,j]) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] Inequalities can be also solved:: sage: solve(x^2>8,x) [[x < -2*sqrt(2)], [x > 2*sqrt(2)]] TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x] Use use_grobner if no solution is obtained from to_poly_solve:: sage: x,y=var('x y'); c1(x,y)=(x-5)^2+y^2-16; c2(x,y)=(y-3)^2+x^2-9 sage: solve([c1(x,y),c2(x,y)],[x,y]) [[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(5)*sqrt(11) + 123/68], [x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(5)*sqrt(11) + 123/68]] """ from sage.symbolic.expression import is_Expression if is_Expression(f): # f is a single expression ans = f.solve(*args,**kwds) return ans elif len(f)==1 and is_Expression(f[0]): # f is a list with a single expression ans = f[0].solve(*args,**kwds) return ans else: # f is a list of such expressions or equations from sage.symbolic.ring import is_SymbolicVariable if len(args)==0: raise TypeError, "Please input variables to solve for." if is_SymbolicVariable(args[0]): variables = args else: variables = tuple(args[0]) for v in variables: if not is_SymbolicVariable(v): raise TypeError, "%s is not a valid variable."%v try: f = [s for s in f if s is not True] except TypeError: raise ValueError, "Unable to solve %s for %s"%(f, args) if any(s is False for s in f): return [] from sage.calculus.calculus import maxima m = maxima(f) try: s = m.solve(variables) except: # if Maxima gave an error, try its to_poly_solve try: s = m.to_poly_solve(variables) except TypeError, mess: # if that gives an error, raise an error. if "Error executing code in Maxima" in str(mess): raise ValueError, "Sage is unable to determine whether the system %s can be solved for %s"%(f,args) else: raise if len(s)==0: # if Maxima's solve gave no solutions, try its to_poly_solve try: s = m.to_poly_solve(variables) except: # if that gives an error, stick with no solutions s = [] if len(s)==0: # if to_poly_solve gave no solutions, try use_grobner try: s = m.to_poly_solve(variables,'use_grobner=true') except: # if that gives an error, stick with no solutions s = [] sol_list = string_to_list_of_solutions(repr(s)) if 'solution_dict' in kwds and kwds['solution_dict']==True: if isinstance(sol_list[0], list): sol_dict=[dict([[eq.left(),eq.right()] for eq in solution]) for solution in sol_list] else: sol_dict=[{eq.left():eq.right()} for eq in sol_list] return sol_dict else: return sol_list
|
def solve(f, *args, **kwds): r""" Algebraically solve an equation or system of equations (over the complex numbers) for given variables. Inequalities and systems of inequalities are also supported. INPUT: - ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict`` - bool (default: False); if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: x, y = var('x, y') sage: solve([x+y==6, x-y==4], x, y) [[x == 5, y == 1]] sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y) [[x == -1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == -1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 0, y == -1], [x == 0, y == 1]] sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y) [[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]] sage: solutions=solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True) sage: for solution in solutions: print solution[x].n(digits=3), ",", solution[y].n(digits=3) -0.500 - 0.866*I , -1.27 + 0.341*I -0.500 - 0.866*I , 1.27 - 0.341*I -0.500 + 0.866*I , -1.27 - 0.341*I -0.500 + 0.866*I , 1.27 + 0.341*I 0.000 , -1.00 0.000 , 1.00 Whenever possible, answers will be symbolic, but with systems of equations, at times approximations will be given, due to the underlying algorithm in Maxima:: sage: sols = solve([x^3==y,y^2==x],[x,y]); sols[-1], sols[0] ([x == 0, y == 0], [x == (0.309016994375 + 0.951056516295*I), y == (-0.809016994375 - 0.587785252292*I)]) sage: sols[0][0].rhs().pyobject().parent() Complex Double Field If ``f`` is only one equation or expression, we use the solve method for symbolic expressions, which defaults to exact answers only:: sage: solve([y^6==y],y) [y == e^(2/5*I*pi), y == e^(4/5*I*pi), y == e^(-4/5*I*pi), y == e^(-2/5*I*pi), y == 1, y == 0] sage: solve( [y^6 == y], y)==solve( y^6 == y, y) True .. note:: For more details about solving a single equations, see the documentation for its solve. :: sage: from sage.symbolic.expression import Expression sage: Expression.solve(x^2==1,x) [x == -1, x == 1] We must solve with respect to actual variables:: sage: z = 5 sage: solve([8*z + y == 3, -z +7*y == 0],y,z) Traceback (most recent call last): ... TypeError: 5 is not a valid variable. If we ask for dictionaries containing the solutions, we get them:: sage: solve([x^2-1],x,solution_dict=True) [{x: -1}, {x: 1}] sage: solve([x^2-4*x+4],x,solution_dict=True) [{x: 2}] sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True) sage: for soln in res: print "x: %s, y: %s"%(soln[x], soln[y]) x: 2, y: 4 x: -2, y: 4 If there is a parameter in the answer, that will show up as a new variable. In the following example, ``r1`` is a real free variable (because of the ``r``):: sage: solve([x+y == 3, 2*x+2*y == 6],x,y) [[x == -r1 + 3, y == r1]] Especially with trigonometric functions, the dummy variable may be implicitly an integer (hence the ``z``):: sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y) [[x == 1/4*pi + pi*z38, y == -1/4*pi - pi*z38]] Expressions which are not equations are assumed to be set equal to zero, as with `x` in the following example:: sage: solve([x, y == 2],x,y) [[x == 0, y == 2]] If ``True`` appears in the list of equations it is ignored, and if ``False`` appears in the list then no solutions are returned. E.g., note that the first ``3==3`` evaluates to ``True``, not to a symbolic equation. :: sage: solve([3==3, 1.00000000000000*x^3 == 0], x) [x == 0] sage: solve([1.00000000000000*x^3 == 0], x) [x == 0] Here, the first equation evaluates to ``False``, so there are no solutions:: sage: solve([1==3, 1.00000000000000*x^3 == 0], x) [] Completely symbolic solutions are supported:: sage: var('s,j,b,m,g') (s, j, b, m, g) sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ]; sage: solve(sys,s,j) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,(s,j)) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,[s,j]) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] Inequalities can be also solved:: sage: solve(x^2>8,x) [[x < -2*sqrt(2)], [x > 2*sqrt(2)]] TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x] Use use_grobner if no solution is obtained from to_poly_solve:: sage: x,y=var('x y'); c1(x,y)=(x-5)^2+y^2-16; c2(x,y)=(y-3)^2+x^2-9 sage: solve([c1(x,y),c2(x,y)],[x,y]) [[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(5)*sqrt(11) + 123/68], [x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(5)*sqrt(11) + 123/68]] """ from sage.symbolic.expression import is_Expression if is_Expression(f): # f is a single expression ans = f.solve(*args,**kwds) return ans elif len(f)==1 and is_Expression(f[0]): # f is a list with a single expression ans = f[0].solve(*args,**kwds) return ans else: # f is a list of such expressions or equations from sage.symbolic.ring import is_SymbolicVariable if len(args)==0: raise TypeError, "Please input variables to solve for." if is_SymbolicVariable(args[0]): variables = args else: variables = tuple(args[0]) for v in variables: if not is_SymbolicVariable(v): raise TypeError, "%s is not a valid variable."%v try: f = [s for s in f if s is not True] except TypeError: raise ValueError, "Unable to solve %s for %s"%(f, args) if any(s is False for s in f): return [] from sage.calculus.calculus import maxima m = maxima(f) try: s = m.solve(variables) except: # if Maxima gave an error, try its to_poly_solve try: s = m.to_poly_solve(variables) except TypeError, mess: # if that gives an error, raise an error. if "Error executing code in Maxima" in str(mess): raise ValueError, "Sage is unable to determine whether the system %s can be solved for %s"%(f,args) else: raise if len(s)==0: # if Maxima's solve gave no solutions, try its to_poly_solve try: s = m.to_poly_solve(variables) except: # if that gives an error, stick with no solutions s = [] if len(s)==0: # if to_poly_solve gave no solutions, try use_grobner try: s = m.to_poly_solve(variables,'use_grobner=true') except: # if that gives an error, stick with no solutions s = [] sol_list = string_to_list_of_solutions(repr(s)) if 'solution_dict' in kwds and kwds['solution_dict']==True: if isinstance(sol_list[0], list): sol_dict=[dict([[eq.left(),eq.right()] for eq in solution]) for solution in sol_list] else: sol_dict=[{eq.left():eq.right()} for eq in sol_list] return sol_dict else: return sol_list
| 473,235
|
def solve(f, *args, **kwds): r""" Algebraically solve an equation or system of equations (over the complex numbers) for given variables. Inequalities and systems of inequalities are also supported. INPUT: - ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict`` - bool (default: False); if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: x, y = var('x, y') sage: solve([x+y==6, x-y==4], x, y) [[x == 5, y == 1]] sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y) [[x == -1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == -1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 0, y == -1], [x == 0, y == 1]] sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y) [[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]] sage: solutions=solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True) sage: for solution in solutions: print solution[x].n(digits=3), ",", solution[y].n(digits=3) -0.500 - 0.866*I , -1.27 + 0.341*I -0.500 - 0.866*I , 1.27 - 0.341*I -0.500 + 0.866*I , -1.27 - 0.341*I -0.500 + 0.866*I , 1.27 + 0.341*I 0.000 , -1.00 0.000 , 1.00 Whenever possible, answers will be symbolic, but with systems of equations, at times approximations will be given, due to the underlying algorithm in Maxima:: sage: sols = solve([x^3==y,y^2==x],[x,y]); sols[-1], sols[0] ([x == 0, y == 0], [x == (0.309016994375 + 0.951056516295*I), y == (-0.809016994375 - 0.587785252292*I)]) sage: sols[0][0].rhs().pyobject().parent() Complex Double Field If ``f`` is only one equation or expression, we use the solve method for symbolic expressions, which defaults to exact answers only:: sage: solve([y^6==y],y) [y == e^(2/5*I*pi), y == e^(4/5*I*pi), y == e^(-4/5*I*pi), y == e^(-2/5*I*pi), y == 1, y == 0] sage: solve( [y^6 == y], y)==solve( y^6 == y, y) True .. note:: For more details about solving a single equations, see the documentation for its solve. :: sage: from sage.symbolic.expression import Expression sage: Expression.solve(x^2==1,x) [x == -1, x == 1] We must solve with respect to actual variables:: sage: z = 5 sage: solve([8*z + y == 3, -z +7*y == 0],y,z) Traceback (most recent call last): ... TypeError: 5 is not a valid variable. If we ask for a dictionary for the solutions, we get it:: sage: solve([x^2-1],x,solution_dict=True) [{x: -1}, {x: 1}] sage: solve([x^2-4*x+4],x,solution_dict=True) [{x: 2}] sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True) sage: for soln in res: print "x: %s, y: %s"%(soln[x], soln[y]) x: 2, y: 4 x: -2, y: 4 If there is a parameter in the answer, that will show up as a new variable. In the following example, ``r1`` is a real free variable (because of the ``r``):: sage: solve([x+y == 3, 2*x+2*y == 6],x,y) [[x == -r1 + 3, y == r1]] Especially with trigonometric functions, the dummy variable may be implicitly an integer (hence the ``z``):: sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y) [[x == 1/4*pi + pi*z38, y == -1/4*pi - pi*z38]] Expressions which are not equations are assumed to be set equal to zero, as with `x` in the following example:: sage: solve([x, y == 2],x,y) [[x == 0, y == 2]] If ``True`` appears in the list of equations it is ignored, and if ``False`` appears in the list then no solutions are returned. E.g., note that the first ``3==3`` evaluates to ``True``, not to a symbolic equation. :: sage: solve([3==3, 1.00000000000000*x^3 == 0], x) [x == 0] sage: solve([1.00000000000000*x^3 == 0], x) [x == 0] Here, the first equation evaluates to ``False``, so there are no solutions:: sage: solve([1==3, 1.00000000000000*x^3 == 0], x) [] Completely symbolic solutions are supported:: sage: var('s,j,b,m,g') (s, j, b, m, g) sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ]; sage: solve(sys,s,j) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,(s,j)) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,[s,j]) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] Inequalities can be also solved:: sage: solve(x^2>8,x) [[x < -2*sqrt(2)], [x > 2*sqrt(2)]] TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x] Use use_grobner if no solution is obtained from to_poly_solve:: sage: x,y=var('x y'); c1(x,y)=(x-5)^2+y^2-16; c2(x,y)=(y-3)^2+x^2-9 sage: solve([c1(x,y),c2(x,y)],[x,y]) [[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(5)*sqrt(11) + 123/68], [x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(5)*sqrt(11) + 123/68]] """ from sage.symbolic.expression import is_Expression if is_Expression(f): # f is a single expression ans = f.solve(*args,**kwds) return ans elif len(f)==1 and is_Expression(f[0]): # f is a list with a single expression ans = f[0].solve(*args,**kwds) return ans else: # f is a list of such expressions or equations from sage.symbolic.ring import is_SymbolicVariable if len(args)==0: raise TypeError, "Please input variables to solve for." if is_SymbolicVariable(args[0]): variables = args else: variables = tuple(args[0]) for v in variables: if not is_SymbolicVariable(v): raise TypeError, "%s is not a valid variable."%v try: f = [s for s in f if s is not True] except TypeError: raise ValueError, "Unable to solve %s for %s"%(f, args) if any(s is False for s in f): return [] from sage.calculus.calculus import maxima m = maxima(f) try: s = m.solve(variables) except: # if Maxima gave an error, try its to_poly_solve try: s = m.to_poly_solve(variables) except TypeError, mess: # if that gives an error, raise an error. if "Error executing code in Maxima" in str(mess): raise ValueError, "Sage is unable to determine whether the system %s can be solved for %s"%(f,args) else: raise if len(s)==0: # if Maxima's solve gave no solutions, try its to_poly_solve try: s = m.to_poly_solve(variables) except: # if that gives an error, stick with no solutions s = [] if len(s)==0: # if to_poly_solve gave no solutions, try use_grobner try: s = m.to_poly_solve(variables,'use_grobner=true') except: # if that gives an error, stick with no solutions s = [] sol_list = string_to_list_of_solutions(repr(s)) if 'solution_dict' in kwds and kwds['solution_dict']==True: if isinstance(sol_list[0], list): sol_dict=[dict([[eq.left(),eq.right()] for eq in solution]) for solution in sol_list] else: sol_dict=[{eq.left():eq.right()} for eq in sol_list] return sol_dict else: return sol_list
|
def solve(f, *args, **kwds): r""" Algebraically solve an equation or system of equations (over the complex numbers) for given variables. Inequalities and systems of inequalities are also supported. INPUT: - ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict`` - bool (default: False); if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: x, y = var('x, y') sage: solve([x+y==6, x-y==4], x, y) [[x == 5, y == 1]] sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y) [[x == -1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == -1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 0, y == -1], [x == 0, y == 1]] sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y) [[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]] sage: solutions=solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True) sage: for solution in solutions: print solution[x].n(digits=3), ",", solution[y].n(digits=3) -0.500 - 0.866*I , -1.27 + 0.341*I -0.500 - 0.866*I , 1.27 - 0.341*I -0.500 + 0.866*I , -1.27 - 0.341*I -0.500 + 0.866*I , 1.27 + 0.341*I 0.000 , -1.00 0.000 , 1.00 Whenever possible, answers will be symbolic, but with systems of equations, at times approximations will be given, due to the underlying algorithm in Maxima:: sage: sols = solve([x^3==y,y^2==x],[x,y]); sols[-1], sols[0] ([x == 0, y == 0], [x == (0.309016994375 + 0.951056516295*I), y == (-0.809016994375 - 0.587785252292*I)]) sage: sols[0][0].rhs().pyobject().parent() Complex Double Field If ``f`` is only one equation or expression, we use the solve method for symbolic expressions, which defaults to exact answers only:: sage: solve([y^6==y],y) [y == e^(2/5*I*pi), y == e^(4/5*I*pi), y == e^(-4/5*I*pi), y == e^(-2/5*I*pi), y == 1, y == 0] sage: solve( [y^6 == y], y)==solve( y^6 == y, y) True .. note:: For more details about solving a single equations, see the documentation for its solve. :: sage: from sage.symbolic.expression import Expression sage: Expression.solve(x^2==1,x) [x == -1, x == 1] We must solve with respect to actual variables:: sage: z = 5 sage: solve([8*z + y == 3, -z +7*y == 0],y,z) Traceback (most recent call last): ... TypeError: 5 is not a valid variable. If we ask for a dictionary for the solutions, we get it:: sage: solve([x^2-1],x,solution_dict=True) [{x: -1}, {x: 1}] sage: solve([x^2-4*x+4],x,solution_dict=True) [{x: 2}] sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True) sage: for soln in res: print "x: %s, y: %s"%(soln[x], soln[y]) x: 2, y: 4 x: -2, y: 4 If there is a parameter in the answer, that will show up as a new variable. In the following example, ``r1`` is a real free variable (because of the ``r``):: sage: solve([x+y == 3, 2*x+2*y == 6],x,y) [[x == -r1 + 3, y == r1]] Especially with trigonometric functions, the dummy variable may be implicitly an integer (hence the ``z``):: sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y) [[x == 1/4*pi + pi*z38, y == -1/4*pi - pi*z38]] Expressions which are not equations are assumed to be set equal to zero, as with `x` in the following example:: sage: solve([x, y == 2],x,y) [[x == 0, y == 2]] If ``True`` appears in the list of equations it is ignored, and if ``False`` appears in the list then no solutions are returned. E.g., note that the first ``3==3`` evaluates to ``True``, not to a symbolic equation. :: sage: solve([3==3, 1.00000000000000*x^3 == 0], x) [x == 0] sage: solve([1.00000000000000*x^3 == 0], x) [x == 0] Here, the first equation evaluates to ``False``, so there are no solutions:: sage: solve([1==3, 1.00000000000000*x^3 == 0], x) [] Completely symbolic solutions are supported:: sage: var('s,j,b,m,g') (s, j, b, m, g) sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ]; sage: solve(sys,s,j) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,(s,j)) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,[s,j]) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] Inequalities can be also solved:: sage: solve(x^2>8,x) [[x < -2*sqrt(2)], [x > 2*sqrt(2)]] Use use_grobner if no solution is obtained from to_poly_solve:: sage: x,y=var('x y'); c1(x,y)=(x-5)^2+y^2-16; c2(x,y)=(y-3)^2+x^2-9 sage: solve([c1(x,y),c2(x,y)],[x,y]) [[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(5)*sqrt(11) + 123/68], [x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(5)*sqrt(11) + 123/68]] """ from sage.symbolic.expression import is_Expression if is_Expression(f): # f is a single expression ans = f.solve(*args,**kwds) return ans elif len(f)==1 and is_Expression(f[0]): # f is a list with a single expression ans = f[0].solve(*args,**kwds) return ans else: # f is a list of such expressions or equations from sage.symbolic.ring import is_SymbolicVariable if len(args)==0: raise TypeError, "Please input variables to solve for." if is_SymbolicVariable(args[0]): variables = args else: variables = tuple(args[0]) for v in variables: if not is_SymbolicVariable(v): raise TypeError, "%s is not a valid variable."%v try: f = [s for s in f if s is not True] except TypeError: raise ValueError, "Unable to solve %s for %s"%(f, args) if any(s is False for s in f): return [] from sage.calculus.calculus import maxima m = maxima(f) try: s = m.solve(variables) except: # if Maxima gave an error, try its to_poly_solve try: s = m.to_poly_solve(variables) except TypeError, mess: # if that gives an error, raise an error. if "Error executing code in Maxima" in str(mess): raise ValueError, "Sage is unable to determine whether the system %s can be solved for %s"%(f,args) else: raise if len(s)==0: # if Maxima's solve gave no solutions, try its to_poly_solve try: s = m.to_poly_solve(variables) except: # if that gives an error, stick with no solutions s = [] if len(s)==0: # if to_poly_solve gave no solutions, try use_grobner try: s = m.to_poly_solve(variables,'use_grobner=true') except: # if that gives an error, stick with no solutions s = [] sol_list = string_to_list_of_solutions(repr(s)) if 'solution_dict' in kwds and kwds['solution_dict']==True: if isinstance(sol_list[0], list): sol_dict=[dict([[eq.left(),eq.right()] for eq in solution]) for solution in sol_list] else: sol_dict=[{eq.left():eq.right()} for eq in sol_list] return sol_dict else: return sol_list
| 473,236
|
def solve(f, *args, **kwds): r""" Algebraically solve an equation or system of equations (over the complex numbers) for given variables. Inequalities and systems of inequalities are also supported. INPUT: - ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict`` - bool (default: False); if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: x, y = var('x, y') sage: solve([x+y==6, x-y==4], x, y) [[x == 5, y == 1]] sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y) [[x == -1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == -1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 0, y == -1], [x == 0, y == 1]] sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y) [[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]] sage: solutions=solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True) sage: for solution in solutions: print solution[x].n(digits=3), ",", solution[y].n(digits=3) -0.500 - 0.866*I , -1.27 + 0.341*I -0.500 - 0.866*I , 1.27 - 0.341*I -0.500 + 0.866*I , -1.27 - 0.341*I -0.500 + 0.866*I , 1.27 + 0.341*I 0.000 , -1.00 0.000 , 1.00 Whenever possible, answers will be symbolic, but with systems of equations, at times approximations will be given, due to the underlying algorithm in Maxima:: sage: sols = solve([x^3==y,y^2==x],[x,y]); sols[-1], sols[0] ([x == 0, y == 0], [x == (0.309016994375 + 0.951056516295*I), y == (-0.809016994375 - 0.587785252292*I)]) sage: sols[0][0].rhs().pyobject().parent() Complex Double Field If ``f`` is only one equation or expression, we use the solve method for symbolic expressions, which defaults to exact answers only:: sage: solve([y^6==y],y) [y == e^(2/5*I*pi), y == e^(4/5*I*pi), y == e^(-4/5*I*pi), y == e^(-2/5*I*pi), y == 1, y == 0] sage: solve( [y^6 == y], y)==solve( y^6 == y, y) True .. note:: For more details about solving a single equations, see the documentation for its solve. :: sage: from sage.symbolic.expression import Expression sage: Expression.solve(x^2==1,x) [x == -1, x == 1] We must solve with respect to actual variables:: sage: z = 5 sage: solve([8*z + y == 3, -z +7*y == 0],y,z) Traceback (most recent call last): ... TypeError: 5 is not a valid variable. If we ask for a dictionary for the solutions, we get it:: sage: solve([x^2-1],x,solution_dict=True) [{x: -1}, {x: 1}] sage: solve([x^2-4*x+4],x,solution_dict=True) [{x: 2}] sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True) sage: for soln in res: print "x: %s, y: %s"%(soln[x], soln[y]) x: 2, y: 4 x: -2, y: 4 If there is a parameter in the answer, that will show up as a new variable. In the following example, ``r1`` is a real free variable (because of the ``r``):: sage: solve([x+y == 3, 2*x+2*y == 6],x,y) [[x == -r1 + 3, y == r1]] Especially with trigonometric functions, the dummy variable may be implicitly an integer (hence the ``z``):: sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y) [[x == 1/4*pi + pi*z38, y == -1/4*pi - pi*z38]] Expressions which are not equations are assumed to be set equal to zero, as with `x` in the following example:: sage: solve([x, y == 2],x,y) [[x == 0, y == 2]] If ``True`` appears in the list of equations it is ignored, and if ``False`` appears in the list then no solutions are returned. E.g., note that the first ``3==3`` evaluates to ``True``, not to a symbolic equation. :: sage: solve([3==3, 1.00000000000000*x^3 == 0], x) [x == 0] sage: solve([1.00000000000000*x^3 == 0], x) [x == 0] Here, the first equation evaluates to ``False``, so there are no solutions:: sage: solve([1==3, 1.00000000000000*x^3 == 0], x) [] Completely symbolic solutions are supported:: sage: var('s,j,b,m,g') (s, j, b, m, g) sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ]; sage: solve(sys,s,j) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,(s,j)) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,[s,j]) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] Inequalities can be also solved:: sage: solve(x^2>8,x) [[x < -2*sqrt(2)], [x > 2*sqrt(2)]] TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x] Use use_grobner if no solution is obtained from to_poly_solve:: sage: x,y=var('x y'); c1(x,y)=(x-5)^2+y^2-16; c2(x,y)=(y-3)^2+x^2-9 sage: solve([c1(x,y),c2(x,y)],[x,y]) [[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(5)*sqrt(11) + 123/68], [x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(5)*sqrt(11) + 123/68]] """ from sage.symbolic.expression import is_Expression if is_Expression(f): # f is a single expression ans = f.solve(*args,**kwds) return ans elif len(f)==1 and is_Expression(f[0]): # f is a list with a single expression ans = f[0].solve(*args,**kwds) return ans else: # f is a list of such expressions or equations from sage.symbolic.ring import is_SymbolicVariable if len(args)==0: raise TypeError, "Please input variables to solve for." if is_SymbolicVariable(args[0]): variables = args else: variables = tuple(args[0]) for v in variables: if not is_SymbolicVariable(v): raise TypeError, "%s is not a valid variable."%v try: f = [s for s in f if s is not True] except TypeError: raise ValueError, "Unable to solve %s for %s"%(f, args) if any(s is False for s in f): return [] from sage.calculus.calculus import maxima m = maxima(f) try: s = m.solve(variables) except: # if Maxima gave an error, try its to_poly_solve try: s = m.to_poly_solve(variables) except TypeError, mess: # if that gives an error, raise an error. if "Error executing code in Maxima" in str(mess): raise ValueError, "Sage is unable to determine whether the system %s can be solved for %s"%(f,args) else: raise if len(s)==0: # if Maxima's solve gave no solutions, try its to_poly_solve try: s = m.to_poly_solve(variables) except: # if that gives an error, stick with no solutions s = [] if len(s)==0: # if to_poly_solve gave no solutions, try use_grobner try: s = m.to_poly_solve(variables,'use_grobner=true') except: # if that gives an error, stick with no solutions s = [] sol_list = string_to_list_of_solutions(repr(s)) if 'solution_dict' in kwds and kwds['solution_dict']==True: if isinstance(sol_list[0], list): sol_dict=[dict([[eq.left(),eq.right()] for eq in solution]) for solution in sol_list] else: sol_dict=[{eq.left():eq.right()} for eq in sol_list] return sol_dict else: return sol_list
|
def solve(f, *args, **kwds): r""" Algebraically solve an equation or system of equations (over the complex numbers) for given variables. Inequalities and systems of inequalities are also supported. INPUT: - ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict`` - bool (default: False); if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: x, y = var('x, y') sage: solve([x+y==6, x-y==4], x, y) [[x == 5, y == 1]] sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y) [[x == -1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == -1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(-I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == -1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 1/2*I*sqrt(3) - 1/2, y == 1/2*sqrt(I*sqrt(3) + 3)*sqrt(2)], [x == 0, y == -1], [x == 0, y == 1]] sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y) [[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]] sage: solutions=solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True) sage: for solution in solutions: print solution[x].n(digits=3), ",", solution[y].n(digits=3) -0.500 - 0.866*I , -1.27 + 0.341*I -0.500 - 0.866*I , 1.27 - 0.341*I -0.500 + 0.866*I , -1.27 - 0.341*I -0.500 + 0.866*I , 1.27 + 0.341*I 0.000 , -1.00 0.000 , 1.00 Whenever possible, answers will be symbolic, but with systems of equations, at times approximations will be given, due to the underlying algorithm in Maxima:: sage: sols = solve([x^3==y,y^2==x],[x,y]); sols[-1], sols[0] ([x == 0, y == 0], [x == (0.309016994375 + 0.951056516295*I), y == (-0.809016994375 - 0.587785252292*I)]) sage: sols[0][0].rhs().pyobject().parent() Complex Double Field If ``f`` is only one equation or expression, we use the solve method for symbolic expressions, which defaults to exact answers only:: sage: solve([y^6==y],y) [y == e^(2/5*I*pi), y == e^(4/5*I*pi), y == e^(-4/5*I*pi), y == e^(-2/5*I*pi), y == 1, y == 0] sage: solve( [y^6 == y], y)==solve( y^6 == y, y) True .. note:: For more details about solving a single equations, see the documentation for its solve. :: sage: from sage.symbolic.expression import Expression sage: Expression.solve(x^2==1,x) [x == -1, x == 1] We must solve with respect to actual variables:: sage: z = 5 sage: solve([8*z + y == 3, -z +7*y == 0],y,z) Traceback (most recent call last): ... TypeError: 5 is not a valid variable. If we ask for a dictionary for the solutions, we get it:: sage: solve([x^2-1],x,solution_dict=True) [{x: -1}, {x: 1}] sage: solve([x^2-4*x+4],x,solution_dict=True) [{x: 2}] sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True) sage: for soln in res: print "x: %s, y: %s"%(soln[x], soln[y]) x: 2, y: 4 x: -2, y: 4 If there is a parameter in the answer, that will show up as a new variable. In the following example, ``r1`` is a real free variable (because of the ``r``):: sage: solve([x+y == 3, 2*x+2*y == 6],x,y) [[x == -r1 + 3, y == r1]] Especially with trigonometric functions, the dummy variable may be implicitly an integer (hence the ``z``):: sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y) [[x == 1/4*pi + pi*z38, y == -1/4*pi - pi*z38]] Expressions which are not equations are assumed to be set equal to zero, as with `x` in the following example:: sage: solve([x, y == 2],x,y) [[x == 0, y == 2]] If ``True`` appears in the list of equations it is ignored, and if ``False`` appears in the list then no solutions are returned. E.g., note that the first ``3==3`` evaluates to ``True``, not to a symbolic equation. :: sage: solve([3==3, 1.00000000000000*x^3 == 0], x) [x == 0] sage: solve([1.00000000000000*x^3 == 0], x) [x == 0] Here, the first equation evaluates to ``False``, so there are no solutions:: sage: solve([1==3, 1.00000000000000*x^3 == 0], x) [] Completely symbolic solutions are supported:: sage: var('s,j,b,m,g') (s, j, b, m, g) sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ]; sage: solve(sys,s,j) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,(s,j)) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,[s,j]) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] Inequalities can be also solved:: sage: solve(x^2>8,x) [[x < -2*sqrt(2)], [x > 2*sqrt(2)]] TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x] Use use_grobner if no solution is obtained from to_poly_solve:: sage: x,y=var('x y'); c1(x,y)=(x-5)^2+y^2-16; c2(x,y)=(y-3)^2+x^2-9 sage: solve([c1(x,y),c2(x,y)],[x,y]) [[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(5)*sqrt(11) + 123/68], [x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(5)*sqrt(11) + 123/68]] """ from sage.symbolic.expression import is_Expression if is_Expression(f): # f is a single expression ans = f.solve(*args,**kwds) return ans elif len(f)==1 and is_Expression(f[0]): # f is a list with a single expression ans = f[0].solve(*args,**kwds) return ans else: # f is a list of such expressions or equations from sage.symbolic.ring import is_SymbolicVariable if len(args)==0: raise TypeError, "Please input variables to solve for." if is_SymbolicVariable(args[0]): variables = args else: variables = tuple(args[0]) for v in variables: if not is_SymbolicVariable(v): raise TypeError, "%s is not a valid variable."%v try: f = [s for s in f if s is not True] except TypeError: raise ValueError, "Unable to solve %s for %s"%(f, args) if any(s is False for s in f): return [] from sage.calculus.calculus import maxima m = maxima(f) try: s = m.solve(variables) except: # if Maxima gave an error, try its to_poly_solve try: s = m.to_poly_solve(variables) except TypeError, mess: # if that gives an error, raise an error. if "Error executing code in Maxima" in str(mess): raise ValueError, "Sage is unable to determine whether the system %s can be solved for %s"%(f,args) else: raise if len(s)==0: # if Maxima's solve gave no solutions, try its to_poly_solve try: s = m.to_poly_solve(variables) except: # if that gives an error, stick with no solutions s = [] if len(s)==0: # if to_poly_solve gave no solutions, try use_grobner try: s = m.to_poly_solve(variables,'use_grobner=true') except: # if that gives an error, stick with no solutions s = [] sol_list = string_to_list_of_solutions(repr(s)) if kwds.get('solution_dict', False): if len(sol_list)==0: return [] if isinstance(sol_list[0], list): sol_dict=[dict([[eq.left(),eq.right()] for eq in solution]) for solution in sol_list] else: sol_dict=[{eq.left():eq.right()} for eq in sol_list] return sol_dict else: return sol_list
| 473,237
|
def solve_mod(eqns, modulus, solution_dict = False): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. By default the solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer - ``solution_dict`` - (default: False) if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We can solve with respect to a bigger modulus if it consists only of small prime factors:: sage: [d] = solve_mod([5*x + y == 3, 2*x - 3*y == 9], 3*5*7*11*19*23*29, solution_dict = True) sage: d[x] 12915279 sage: d[y] 8610183 We solve an simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: The current implementation splits the modulus into prime powers, then naively enumerates all possible solutions and finally combines the solution using the Chinese Remainder Theorem. The interface is good, but the algorithm is horrible if the modulus has some larger prime factors! Sage *does* have the ability to do something much faster in certain cases at least by using Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At least it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing, factor, crt_basis from sage.misc.all import cartesian_product_iterator from sage.modules.all import vector from sage.matrix.all import matrix if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) factors = [p**i for p,i in factor(modulus)] crt_basis = vector(Integers(modulus), crt_basis(factors)) solutions = [solve_mod_enumerate(eqns, p) for p in factors] ans = [] for solution in cartesian_product_iterator(solutions): solution_mat = matrix(Integers(modulus), solution) ans.append(tuple(c.dot_product(crt_basis) for c in solution_mat.columns())) if solution_dict == True: sol_dict = [dict(zip(vars, solution)) for solution in ans] return sol_dict else: return ans
|
def solve_mod(eqns, modulus, solution_dict = False): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. By default the solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer - ``solution_dict`` - bool (default: False); if True or non-zero, return a list of dictionaries containing the solutions. If there are no solutions, return an empty list (rather than a list containing an empty dictionary). Likewise, if there's only a single solution, return a list containing one dictionary with that solution. EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We can solve with respect to a bigger modulus if it consists only of small prime factors:: sage: [d] = solve_mod([5*x + y == 3, 2*x - 3*y == 9], 3*5*7*11*19*23*29, solution_dict = True) sage: d[x] 12915279 sage: d[y] 8610183 We solve an simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: The current implementation splits the modulus into prime powers, then naively enumerates all possible solutions and finally combines the solution using the Chinese Remainder Theorem. The interface is good, but the algorithm is horrible if the modulus has some larger prime factors! Sage *does* have the ability to do something much faster in certain cases at least by using Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At least it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing, factor, crt_basis from sage.misc.all import cartesian_product_iterator from sage.modules.all import vector from sage.matrix.all import matrix if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) factors = [p**i for p,i in factor(modulus)] crt_basis = vector(Integers(modulus), crt_basis(factors)) solutions = [solve_mod_enumerate(eqns, p) for p in factors] ans = [] for solution in cartesian_product_iterator(solutions): solution_mat = matrix(Integers(modulus), solution) ans.append(tuple(c.dot_product(crt_basis) for c in solution_mat.columns())) if solution_dict == True: sol_dict = [dict(zip(vars, solution)) for solution in ans] return sol_dict else: return ans
| 473,238
|
def solve_mod(eqns, modulus, solution_dict = False): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. By default the solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer - ``solution_dict`` - (default: False) if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We can solve with respect to a bigger modulus if it consists only of small prime factors:: sage: [d] = solve_mod([5*x + y == 3, 2*x - 3*y == 9], 3*5*7*11*19*23*29, solution_dict = True) sage: d[x] 12915279 sage: d[y] 8610183 We solve an simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: The current implementation splits the modulus into prime powers, then naively enumerates all possible solutions and finally combines the solution using the Chinese Remainder Theorem. The interface is good, but the algorithm is horrible if the modulus has some larger prime factors! Sage *does* have the ability to do something much faster in certain cases at least by using Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At least it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing, factor, crt_basis from sage.misc.all import cartesian_product_iterator from sage.modules.all import vector from sage.matrix.all import matrix if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) factors = [p**i for p,i in factor(modulus)] crt_basis = vector(Integers(modulus), crt_basis(factors)) solutions = [solve_mod_enumerate(eqns, p) for p in factors] ans = [] for solution in cartesian_product_iterator(solutions): solution_mat = matrix(Integers(modulus), solution) ans.append(tuple(c.dot_product(crt_basis) for c in solution_mat.columns())) if solution_dict == True: sol_dict = [dict(zip(vars, solution)) for solution in ans] return sol_dict else: return ans
|
def solve_mod(eqns, modulus, solution_dict = False): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. By default the solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer - ``solution_dict`` - (default: False) if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We can solve with respect to a bigger modulus if it consists only of small prime factors:: sage: [d] = solve_mod([5*x + y == 3, 2*x - 3*y == 9], 3*5*7*11*19*23*29, solution_dict = True) sage: d[x] 12915279 sage: d[y] 8610183 We solve a simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: The current implementation splits the modulus into prime powers, then naively enumerates all possible solutions and finally combines the solution using the Chinese Remainder Theorem. The interface is good, but the algorithm is horrible if the modulus has some larger prime factors! Sage *does* have the ability to do something much faster in certain cases at least by using Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At least it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing, factor, crt_basis from sage.misc.all import cartesian_product_iterator from sage.modules.all import vector from sage.matrix.all import matrix if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) factors = [p**i for p,i in factor(modulus)] crt_basis = vector(Integers(modulus), crt_basis(factors)) solutions = [solve_mod_enumerate(eqns, p) for p in factors] ans = [] for solution in cartesian_product_iterator(solutions): solution_mat = matrix(Integers(modulus), solution) ans.append(tuple(c.dot_product(crt_basis) for c in solution_mat.columns())) if solution_dict == True: sol_dict = [dict(zip(vars, solution)) for solution in ans] return sol_dict else: return ans
| 473,239
|
def solve_mod(eqns, modulus, solution_dict = False): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. By default the solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer - ``solution_dict`` - (default: False) if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We can solve with respect to a bigger modulus if it consists only of small prime factors:: sage: [d] = solve_mod([5*x + y == 3, 2*x - 3*y == 9], 3*5*7*11*19*23*29, solution_dict = True) sage: d[x] 12915279 sage: d[y] 8610183 We solve an simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: The current implementation splits the modulus into prime powers, then naively enumerates all possible solutions and finally combines the solution using the Chinese Remainder Theorem. The interface is good, but the algorithm is horrible if the modulus has some larger prime factors! Sage *does* have the ability to do something much faster in certain cases at least by using Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At least it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing, factor, crt_basis from sage.misc.all import cartesian_product_iterator from sage.modules.all import vector from sage.matrix.all import matrix if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) factors = [p**i for p,i in factor(modulus)] crt_basis = vector(Integers(modulus), crt_basis(factors)) solutions = [solve_mod_enumerate(eqns, p) for p in factors] ans = [] for solution in cartesian_product_iterator(solutions): solution_mat = matrix(Integers(modulus), solution) ans.append(tuple(c.dot_product(crt_basis) for c in solution_mat.columns())) if solution_dict == True: sol_dict = [dict(zip(vars, solution)) for solution in ans] return sol_dict else: return ans
|
def solve_mod(eqns, modulus, solution_dict = False): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. By default the solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer - ``solution_dict`` - (default: False) if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We can solve with respect to a bigger modulus if it consists only of small prime factors:: sage: [d] = solve_mod([5*x + y == 3, 2*x - 3*y == 9], 3*5*7*11*19*23*29, solution_dict = True) sage: d[x] 12915279 sage: d[y] 8610183 We solve an simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: The current implementation splits the modulus into prime powers, then naively enumerates all possible solutions and finally combines the solution using the Chinese Remainder Theorem. The interface is good, but the algorithm is horrible if the modulus has some larger prime factors! Sage *does* have the ability to do something much faster in certain cases at least by using Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At least it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing, factor, crt_basis from sage.misc.all import cartesian_product_iterator from sage.modules.all import vector from sage.matrix.all import matrix if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) factors = [p**i for p,i in factor(modulus)] crt_basis = vector(Integers(modulus), crt_basis(factors)) solutions = [solve_mod_enumerate(eqns, p) for p in factors] ans = [] for solution in cartesian_product_iterator(solutions): solution_mat = matrix(Integers(modulus), solution) ans.append(tuple(c.dot_product(crt_basis) for c in solution_mat.columns())) if solution_dict == True: sol_dict = [dict(zip(vars, solution)) for solution in ans] return sol_dict else: return ans
| 473,240
|
def solve_mod(eqns, modulus, solution_dict = False): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. By default the solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer - ``solution_dict`` - (default: False) if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We can solve with respect to a bigger modulus if it consists only of small prime factors:: sage: [d] = solve_mod([5*x + y == 3, 2*x - 3*y == 9], 3*5*7*11*19*23*29, solution_dict = True) sage: d[x] 12915279 sage: d[y] 8610183 We solve an simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: The current implementation splits the modulus into prime powers, then naively enumerates all possible solutions and finally combines the solution using the Chinese Remainder Theorem. The interface is good, but the algorithm is horrible if the modulus has some larger prime factors! Sage *does* have the ability to do something much faster in certain cases at least by using Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At least it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing, factor, crt_basis from sage.misc.all import cartesian_product_iterator from sage.modules.all import vector from sage.matrix.all import matrix if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) factors = [p**i for p,i in factor(modulus)] crt_basis = vector(Integers(modulus), crt_basis(factors)) solutions = [solve_mod_enumerate(eqns, p) for p in factors] ans = [] for solution in cartesian_product_iterator(solutions): solution_mat = matrix(Integers(modulus), solution) ans.append(tuple(c.dot_product(crt_basis) for c in solution_mat.columns())) if solution_dict == True: sol_dict = [dict(zip(vars, solution)) for solution in ans] return sol_dict else: return ans
|
def solve_mod(eqns, modulus, solution_dict = False): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. By default the solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer - ``solution_dict`` - (default: False) if True, return a list of dictionaries containing the solutions. EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We can solve with respect to a bigger modulus if it consists only of small prime factors:: sage: [d] = solve_mod([5*x + y == 3, 2*x - 3*y == 9], 3*5*7*11*19*23*29, solution_dict = True) sage: d[x] 12915279 sage: d[y] 8610183 We solve an simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: The current implementation splits the modulus into prime powers, then naively enumerates all possible solutions and finally combines the solution using the Chinese Remainder Theorem. The interface is good, but the algorithm is horrible if the modulus has some larger prime factors! Sage *does* have the ability to do something much faster in certain cases at least by using Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At least it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing, factor, crt_basis from sage.misc.all import cartesian_product_iterator from sage.modules.all import vector from sage.matrix.all import matrix if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) factors = [p**i for p,i in factor(modulus)] crt_basis = vector(Integers(modulus), crt_basis(factors)) solutions = [solve_mod_enumerate(eqns, p) for p in factors] ans = [] for solution in cartesian_product_iterator(solutions): solution_mat = matrix(Integers(modulus), solution) ans.append(tuple(c.dot_product(crt_basis) for c in solution_mat.columns())) if solution_dict: sol_dict = [dict(zip(vars, solution)) for solution in ans] return sol_dict else: return ans
| 473,241
|
def solve_mod_enumerate(eqns, modulus): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. The solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We solve an simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: Currently this naively enumerates all possible solutions. The interface is good, but the algorithm is horrible if the modulus is at all large! Sage *does* have the ability to do something much faster in certain cases at least by using the Chinese Remainder Theorem, Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At the very least, it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing from sage.symbolic.expression import is_Expression from sage.misc.all import cartesian_product_iterator if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) R = Integers(modulus) S = PolynomialRing(R, len(vars), vars) eqns_mod = [S(eq) if is_Expression(eq) else S(eq.lhs() - eq.rhs()) for eq in eqns] ans = [] for t in cartesian_product_iterator([R]*len(vars)): is_soln = True for e in eqns_mod: if e(t) != 0: is_soln = False break if is_soln: ans.append(t) return ans
|
def solve_mod_enumerate(eqns, modulus): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. The solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We solve a simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: Currently this naively enumerates all possible solutions. The interface is good, but the algorithm is horrible if the modulus is at all large! Sage *does* have the ability to do something much faster in certain cases at least by using the Chinese Remainder Theorem, Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At the very least, it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing from sage.symbolic.expression import is_Expression from sage.misc.all import cartesian_product_iterator if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) R = Integers(modulus) S = PolynomialRing(R, len(vars), vars) eqns_mod = [S(eq) if is_Expression(eq) else S(eq.lhs() - eq.rhs()) for eq in eqns] ans = [] for t in cartesian_product_iterator([R]*len(vars)): is_soln = True for e in eqns_mod: if e(t) != 0: is_soln = False break if is_soln: ans.append(t) return ans
| 473,242
|
def solve_mod_enumerate(eqns, modulus): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. The solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We solve an simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: Currently this naively enumerates all possible solutions. The interface is good, but the algorithm is horrible if the modulus is at all large! Sage *does* have the ability to do something much faster in certain cases at least by using the Chinese Remainder Theorem, Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At the very least, it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing from sage.symbolic.expression import is_Expression from sage.misc.all import cartesian_product_iterator if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) R = Integers(modulus) S = PolynomialRing(R, len(vars), vars) eqns_mod = [S(eq) if is_Expression(eq) else S(eq.lhs() - eq.rhs()) for eq in eqns] ans = [] for t in cartesian_product_iterator([R]*len(vars)): is_soln = True for e in eqns_mod: if e(t) != 0: is_soln = False break if is_soln: ans.append(t) return ans
|
def solve_mod_enumerate(eqns, modulus): r""" Return all solutions to an equation or list of equations modulo the given integer modulus. Each equation must involve only polynomials in 1 or many variables. The solutions are returned as `n`-tuples, where `n` is the number of variables appearing anywhere in the given equations. The variables are in alphabetical order. INPUT: - ``eqns`` - equation or list of equations - ``modulus`` - an integer EXAMPLES:: sage: var('x,y') (x, y) sage: solve_mod([x^2 + 2 == x, x^2 + y == y^2], 14) [(4, 2), (4, 6), (4, 9), (4, 13)] sage: solve_mod([x^2 == 1, 4*x == 11], 15) [(14,)] Fermat's equation modulo 3 with exponent 5:: sage: var('x,y,z') (x, y, z) sage: solve_mod([x^5 + y^5 == z^5], 3) [(0, 0, 0), (0, 1, 1), (0, 2, 2), (1, 0, 1), (1, 1, 2), (1, 2, 0), (2, 0, 2), (2, 1, 0), (2, 2, 1)] We solve an simple equation modulo 2:: sage: x,y = var('x,y') sage: solve_mod([x == y], 2) [(0, 0), (1, 1)] .. warning:: Currently this naively enumerates all possible solutions. The interface is good, but the algorithm is horrible if the modulus is at all large! Sage *does* have the ability to do something much faster in certain cases at least by using the Chinese Remainder Theorem, Groebner basis, linear algebra techniques, etc. But for a lot of toy problems this function as is might be useful. At the very least, it establishes an interface. """ from sage.rings.all import Integer, Integers, PolynomialRing from sage.symbolic.expression import is_Expression from sage.misc.all import cartesian_product_iterator if not isinstance(eqns, (list, tuple)): eqns = [eqns] modulus = Integer(modulus) if modulus < 1: raise ValueError, "the modulus must be a positive integer" vars = list(set(sum([list(e.variables()) for e in eqns], []))) vars.sort(cmp = lambda x,y: cmp(repr(x), repr(y))) n = len(vars) R = Integers(modulus) S = PolynomialRing(R, len(vars), vars) eqns_mod = [S(eq) if is_Expression(eq) else S(eq.lhs() - eq.rhs()) for eq in eqns] ans = [] for t in cartesian_product_iterator([R]*len(vars)): is_soln = True for e in eqns_mod: if e(t) != 0: is_soln = False break if is_soln: ans.append(t) return ans
| 473,243
|
def __cmp__(self, other): P = self.parent() if P.eval("%s %s %s"%(self.name(), P._equality_symbol(), other.name())) == P._true_symbol(): return 0 elif P.eval("%s %s %s"%(self.name(), P._lessthan_symbol(), other.name())) == P._true_symbol(): return -1 elif P.eval("%s %s %s"%(self.name(), P._greaterthan_symbol(), other.name())) == P._true_symbol(): return 1
|
def __cmp__(self, other): P = self.parent() if P.eval("%s %s %s"%(self.name(), P._equality_symbol(), other.name())) == P._true_symbol(): return 0 elif P.eval("%s %s %s"%(self.name(), P._lessthan_symbol(), other.name())) == P._true_symbol(): return -1 elif P.eval("%s %s %s"%(self.name(), P._greaterthan_symbol(), other.name())) == P._true_symbol(): return 1
| 473,244
|
def _sympy_(self): """ Converts pi to sympy pi.
|
def _sympy_(self): """ Converts pi to sympy pi.
| 473,245
|
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain.
|
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain.
| 473,246
|
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain.
|
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain.
| 473,247
|
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain.
|
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain.
| 473,248
|
def global_integral_model(self): r""" Return a model of self which is integral at all primes.
|
def global_integral_model(self): r""" Return a model of self which is integral at all primes.
| 473,249
|
def install_package(package=None, force=False): """ Install a package or return a list of all packages that have been installed into this Sage install. You must have an internet connection. Also, you will have to restart Sage for the changes to take affect. It is not needed to provide the version number. INPUT: - ``package`` - optional; if specified, install the given package. If not, list all installed packages. IMPLEMENTATION: calls 'sage -f'. .. seealso:: :func:`optional_packages`, :func:`upgrade` """ global __installed_packages if os.uname()[0][:6] == 'CYGWIN': print "install_package may not work correctly under Microsoft Windows" print "since you can't change an opened file. Quit all" print "instances of sage and use 'sage -i' instead or" print "use the force option to install_package." return if package is None: if __installed_packages is None: X = os.popen('sage -f').read().split('\n') i = X.index('Currently installed packages:') X = [Y for Y in X[i+1:] if Y != ''] X.sort() __installed_packages = X return __installed_packages # Get full package name if force: S = [P for P in standard_packages()[0] if P.startswith(package)] O = [P for P in optional_packages()[0] if P.startswith(package)] E = [P for P in experimental_packages()[0] if P.startswith(package)] else: S,O,E = [], [], [] S.extend([P for P in standard_packages()[1] if P.startswith(package)]) O.extend([P for P in optional_packages()[1] if P.startswith(package)]) E.extend([P for P in experimental_packages()[1] if P.startswith(package)]) L = S+O+E if len(L)>1: if force: print "Possible package names starting with '%s' are:"%(package) else: print "Possible names of non-installed packages starting with '%s':"%(package) for P in L: print " ", P raise ValueError, "There is more than one package name starting with '%s'. Please specify!"%(package) if len(L)==0: if not force: if is_package_installed(package): raise ValueError, "Package is already installed. Try install_package('%s',force=True)"%(package) raise ValueError, "There is no package name starting with '%s'."%(package) os.system('sage -f "%s"'%(L[0])) __installed_packages = None
|
def install_package(package=None, force=False): """ Install a package or return a list of all packages that have been installed into this Sage install. You must have an internet connection. Also, you will have to restart Sage for the changes to take affect. It is not needed to provide the version number. INPUT: - ``package`` - optional; if specified, install the given package. If not, list all installed packages. IMPLEMENTATION: calls 'sage -f'. .. seealso:: :func:`optional_packages`, :func:`upgrade` """ global __installed_packages if os.uname()[0][:6] == 'CYGWIN' and package is not None: print "install_package may not work correctly under Microsoft Windows" print "since you can't change an opened file. Quit all" print "instances of sage and use 'sage -i' instead or" print "use the force option to install_package." return if package is None: if __installed_packages is None: X = os.popen('sage -f').read().split('\n') i = X.index('Currently installed packages:') X = [Y for Y in X[i+1:] if Y != ''] X.sort() __installed_packages = X return __installed_packages # Get full package name if force: S = [P for P in standard_packages()[0] if P.startswith(package)] O = [P for P in optional_packages()[0] if P.startswith(package)] E = [P for P in experimental_packages()[0] if P.startswith(package)] else: S,O,E = [], [], [] S.extend([P for P in standard_packages()[1] if P.startswith(package)]) O.extend([P for P in optional_packages()[1] if P.startswith(package)]) E.extend([P for P in experimental_packages()[1] if P.startswith(package)]) L = S+O+E if len(L)>1: if force: print "Possible package names starting with '%s' are:"%(package) else: print "Possible names of non-installed packages starting with '%s':"%(package) for P in L: print " ", P raise ValueError, "There is more than one package name starting with '%s'. Please specify!"%(package) if len(L)==0: if not force: if is_package_installed(package): raise ValueError, "Package is already installed. Try install_package('%s',force=True)"%(package) raise ValueError, "There is no package name starting with '%s'."%(package) os.system('sage -f "%s"'%(L[0])) __installed_packages = None
| 473,250
|
def install_package(package=None, force=False): """ Install a package or return a list of all packages that have been installed into this Sage install. You must have an internet connection. Also, you will have to restart Sage for the changes to take affect. It is not needed to provide the version number. INPUT: - ``package`` - optional; if specified, install the given package. If not, list all installed packages. IMPLEMENTATION: calls 'sage -f'. .. seealso:: :func:`optional_packages`, :func:`upgrade` """ global __installed_packages if os.uname()[0][:6] == 'CYGWIN': print "install_package may not work correctly under Microsoft Windows" print "since you can't change an opened file. Quit all" print "instances of sage and use 'sage -i' instead or" print "use the force option to install_package." return if package is None: if __installed_packages is None: X = os.popen('sage -f').read().split('\n') i = X.index('Currently installed packages:') X = [Y for Y in X[i+1:] if Y != ''] X.sort() __installed_packages = X return __installed_packages # Get full package name if force: S = [P for P in standard_packages()[0] if P.startswith(package)] O = [P for P in optional_packages()[0] if P.startswith(package)] E = [P for P in experimental_packages()[0] if P.startswith(package)] else: S,O,E = [], [], [] S.extend([P for P in standard_packages()[1] if P.startswith(package)]) O.extend([P for P in optional_packages()[1] if P.startswith(package)]) E.extend([P for P in experimental_packages()[1] if P.startswith(package)]) L = S+O+E if len(L)>1: if force: print "Possible package names starting with '%s' are:"%(package) else: print "Possible names of non-installed packages starting with '%s':"%(package) for P in L: print " ", P raise ValueError, "There is more than one package name starting with '%s'. Please specify!"%(package) if len(L)==0: if not force: if is_package_installed(package): raise ValueError, "Package is already installed. Try install_package('%s',force=True)"%(package) raise ValueError, "There is no package name starting with '%s'."%(package) os.system('sage -f "%s"'%(L[0])) __installed_packages = None
|
def install_package(package=None, force=False): """ Install a package or a list of all packages that have been installed into this Sage install. You must have an internet connection. Also, you will have to restart Sage for the changes to take affect. It is not needed to provide the version number. INPUT: - ``package`` - optional; if specified, install the given package. If not, list all installed packages. IMPLEMENTATION: calls 'sage -f'. .. seealso:: :func:`optional_packages`, :func:`upgrade` """ global __installed_packages if os.uname()[0][:6] == 'CYGWIN': print "install_package may not work correctly under Microsoft Windows" print "since you can't change an opened file. Quit all" print "instances of sage and use 'sage -i' instead or" print "use the force option to install_package." if package is None: if __installed_packages is None: X = os.popen('sage -f').read().split('\n') i = X.index('Currently installed packages:') X = [Y for Y in X[i+1:] if Y != ''] X.sort() __installed_packages = X __installed_packages # Get full package name if force: S = [P for P in standard_packages()[0] if P.startswith(package)] O = [P for P in optional_packages()[0] if P.startswith(package)] E = [P for P in experimental_packages()[0] if P.startswith(package)] else: S,O,E = [], [], [] S.extend([P for P in standard_packages()[1] if P.startswith(package)]) O.extend([P for P in optional_packages()[1] if P.startswith(package)]) E.extend([P for P in experimental_packages()[1] if P.startswith(package)]) L = S+O+E if len(L)>1: if force: print "Possible package names starting with '%s' are:"%(package) else: print "Possible names of non-installed packages starting with '%s':"%(package) for P in L: print " ", P raise ValueError, "There is more than one package name starting with '%s'. Please specify!"%(package) if len(L)==0: if not force: if is_package_installed(package): raise ValueError, "Package is already installed. Try install_package('%s',force=True)"%(package) raise ValueError, "There is no package name starting with '%s'."%(package) os.system('sage -f "%s"'%(L[0])) __installed_packages = None
| 473,251
|
def upgrade(): """ Download and build the latest version of Sage. You must have an internet connection. Also, you will have to restart Sage for the changes to take affect. This upgrades to the latest version of core packages (optional packages are not automatically upgraded). This will not work on systems that don't have a C compiler. .. seealso:: :func:`install_package`, :func:`optional_packages` """ global __installed_packages if os.uname()[0][:6] == 'CYGWIN': print "Upgrade may not work correctly under Microsoft Windows" print "since you can't change an opened file. Quit all" print "instances of Sage and use 'sage -upgrade' instead." return os.system('sage -upgrade') __installed_packages = None print "You should quit and restart Sage now."
|
def upgrade(): """ Download and build the latest version of Sage. You must have an internet connection. Also, you will have to restart Sage for the changes to take affect. This upgrades to the latest version of core packages (optional packages are not automatically upgraded). This will not work on systems that don't have a C compiler. .. seealso:: :func:`install_package`, :func:`optional_packages` """ global __installed_packages if os.uname()[0][:6] == 'CYGWIN': print "Upgrade may not work correctly under Microsoft Windows" print "since you can't change an opened file. Quit all" print "instances of Sage and use 'sage -upgrade' instead." return [] os.system('sage -upgrade') __installed_packages = None print "You should quit and restart Sage now."
| 473,252
|
def _ambient_space_point(self, data): r""" Try to convert ``data`` to a point of the ambient space of ``self``.
|
def _ambient_space_point(self, data): r""" Try to convert ``data`` to a point of the ambient space of ``self``.
| 473,253
|
def contains(self, *args): r""" Check if a given point is contained in ``self``.
|
def contains(self, *args): r""" Check if a given point is contained in ``self``.
| 473,254
|
def contains(self, *args): r""" Check if a given point is contained in ``self``.
|
def contains(self, *args): r""" Check if a given point is contained in ``self``.
| 473,255
|
def dual(self): r""" Return the dual cone of ``self``.
|
def dual(self): r""" Return the dual cone of ``self``.
| 473,256
|
def facet_normals(self): r""" Return normals to facets of ``self``.
|
def facet_normals(self): r""" Return normals to facets of ``self``.
| 473,257
|
def _split_ambient_lattice(self): r""" Compute a decomposition of the ``N``-lattice into `N_\sigma` and its complement `N(\sigma)`.
|
def _split_ambient_lattice(self): r""" Compute a decomposition of the ``N``-lattice into `N_\sigma` and its complement `N(\sigma)`.
| 473,258
|
def _split_ambient_lattice(self): r""" Compute a decomposition of the ``N``-lattice into `N_\sigma` and its complement `N(\sigma)`.
|
def _split_ambient_lattice(self): r""" Compute a decomposition of the ``N``-lattice into `N_\sigma` and its complement `N(\sigma)`.
| 473,259
|
def orthogonal_sublattice(self, *args, **kwds): r""" The sublattice (in the dual lattice) orthogonal to the sublattice spanned by the cone.
|
def orthogonal_sublattice(self, *args, **kwds): r""" The sublattice (in the dual lattice) orthogonal to the sublattice spanned by the cone.
| 473,260
|
def spherical_bessel_J(n, var, algorithm="maxima"): r""" Returns the spherical Bessel function of the first kind for integers n -1. Reference: AS 10.1.8 page 437 and AS 10.1.15 page 439. EXAMPLES:: sage: spherical_bessel_J(2,x) ((3/x^2 - 1)*sin(x) - 3*cos(x)/x)/x """ if algorithm=="scipy": import scipy.special ans = str(scipy.special.sph_jn(int(n),float(var))) ans = ans.replace("(","") ans = ans.replace(")","") ans = ans.replace("j","*I") return sage_eval(ans) elif algorithm == 'maxima': _init() return meval("spherical_bessel_j(%s,%s)"%(ZZ(n),var)) else: raise ValueError, "unknown algorithm '%s'"%algorithm
|
def spherical_bessel_J(n, var, algorithm="maxima"): r""" Returns the spherical Bessel function of the first kind for integers n >= 1. Reference: AS 10.1.8 page 437 and AS 10.1.15 page 439. EXAMPLES:: sage: spherical_bessel_J(2,x) ((3/x^2 - 1)*sin(x) - 3*cos(x)/x)/x """ if algorithm=="scipy": import scipy.special ans = str(scipy.special.sph_jn(int(n),float(var))) ans = ans.replace("(","") ans = ans.replace(")","") ans = ans.replace("j","*I") return sage_eval(ans) elif algorithm == 'maxima': _init() return meval("spherical_bessel_j(%s,%s)"%(ZZ(n),var)) else: raise ValueError, "unknown algorithm '%s'"%algorithm
| 473,261
|
def spherical_bessel_J(n, var, algorithm="maxima"): r""" Returns the spherical Bessel function of the first kind for integers n -1. Reference: AS 10.1.8 page 437 and AS 10.1.15 page 439. EXAMPLES:: sage: spherical_bessel_J(2,x) ((3/x^2 - 1)*sin(x) - 3*cos(x)/x)/x """ if algorithm=="scipy": import scipy.special ans = str(scipy.special.sph_jn(int(n),float(var))) ans = ans.replace("(","") ans = ans.replace(")","") ans = ans.replace("j","*I") return sage_eval(ans) elif algorithm == 'maxima': _init() return meval("spherical_bessel_j(%s,%s)"%(ZZ(n),var)) else: raise ValueError, "unknown algorithm '%s'"%algorithm
|
def spherical_bessel_J(n, var, algorithm="maxima"): r""" Returns the spherical Bessel function of the first kind for integers n -1. Reference: AS 10.1.8 page 437 and AS 10.1.15 page 439. EXAMPLES:: sage: spherical_bessel_J(2,x) ((3/x^2 - 1)*sin(x) - 3*cos(x)/x)/x """ if algorithm=="scipy": from scipy.special.specfun import sphj return sphj(int(n), float(var))[1][-1] elif algorithm == 'maxima': _init() return meval("spherical_bessel_j(%s,%s)"%(ZZ(n),var)) else: raise ValueError, "unknown algorithm '%s'"%algorithm
| 473,262
|
def __cmp__(self, other): r""" Define comparison for finite posets.
|
def __hash__(self): """ TESTS:: sage: P = Poset([[1,2],[3],[3]]) sage: P.__hash__() 6557284140853143473 584755121 sage: P = Poset([[1],[3],[3]]) sage: P.__hash__() 5699294501102840900 278031428 """ if self._hash is None: self._hash = tuple(map(tuple, self.cover_relations())).__hash__() return self._hash def __eq__(self, other): r""" Define comparison for finite posets.
| 473,263
|
def __cmp__(self, other): r""" Define comparison for finite posets.
|
def __cmp__(self, other): r""" Define comparison for finite posets.
| 473,264
|
def __cmp__(self, other): r""" Define comparison for finite posets.
|
def __cmp__(self, other): r""" Define comparison for finite posets.
| 473,265
|
def __cmp__(self, other): r""" Define comparison for finite posets.
|
def __cmp__(self, other): r""" Define comparison for finite posets.
| 473,266
|
def __cmp__(self, other): r""" Define comparison for finite posets.
|
def __cmp__(self, other): r""" Define comparison for finite posets.
| 473,267
|
def __cmp__(self, other): r""" Define comparison for finite posets.
|
def __cmp__(self, other): r""" Define comparison for finite posets.
| 473,268
|
def squarefree_part(x): """ Returns the square free part of `x`, i.e., a divisor `z` such that `x = z y^2`, for a perfect square `y^2`. EXAMPLES:: sage: squarefree_part(100) 1 sage: squarefree_part(12) 3 sage: squarefree_part(10) 10 :: sage: x = QQ['x'].0 sage: S = squarefree_part(-9*x*(x-6)^7*(x-3)^2); S -9*x^2 + 54*x sage: S.factor() (-9) * (x - 6) * x :: sage: f = (x^3 + x + 1)^3*(x-1); f x^10 - x^9 + 3*x^8 + 3*x^5 - 2*x^4 - x^3 - 2*x - 1 sage: g = squarefree_part(f); g x^4 - x^3 + x^2 - 1 sage: g.factor() (x - 1) * (x^3 + x + 1) """ try: return x.squarefree_part() except AttributeError: pass F = factor(x) n = x.parent()(1) for p, e in F: if e%2 != 0: n *= p return n * F.unit()
|
def squarefree_part(x): """ Returns the square free part of `x`, i.e., a divisor `z` such that `x = z y^2`, for a perfect square `y^2`. EXAMPLES:: sage: squarefree_part(100) 1 sage: squarefree_part(12) 3 sage: squarefree_part(10) 10 :: sage: x = QQ['x'].0 sage: S = squarefree_part(-9*x*(x-6)^7*(x-3)^2); S -9*x^2 + 54*x sage: S.factor() (-9) * (x - 6) * x :: sage: f = (x^3 + x + 1)^3*(x-1); f x^10 - x^9 + 3*x^8 + 3*x^5 - 2*x^4 - x^3 - 2*x - 1 sage: g = squarefree_part(f); g x^4 - x^3 + x^2 - 1 sage: g.factor() (x - 1) * (x^3 + x + 1) """ try: return x.squarefree_part() except AttributeError: pass F = factor(x) n = parent(x)(1) for p, e in F: if e%2 != 0: n *= p return n * F.unit()
| 473,269
|
def inject_coefficients(self, scope=None, verbose=True): r""" Inject generators of the base field of ``self`` into ``scope``.
|
def inject_coefficients(self, scope=None, verbose=True): r""" Inject generators of the base field of ``self`` into ``scope``.
| 473,270
|
def inject_coefficients(self, scope=None, verbose=True): r""" Inject generators of the base field of ``self`` into ``scope``.
|
def inject_coefficients(self, scope=None, verbose=True): r""" Inject generators of the base field of ``self`` into ``scope``.
| 473,271
|
def inject_coefficients(self, scope=None, verbose=True): r""" Inject generators of the base field of ``self`` into ``scope``.
|
def inject_coefficients(self, scope=None, verbose=True): r""" Inject generators of the base field of ``self`` into ``scope``.
| 473,272
|
def edges(self, labels=True, sort=True, key=None): r""" Return a list of the edges of the graph as triples (u,v,l) where u and v are vertices and l is a label.
|
def edges(self, labels=True, sort=True, key=None): r""" Return a list of the edges of the graph as triples (u,v,l) where u and v are vertices and l is a label.
| 473,273
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
|
def edge_boundary(self, vertices1, vertices2=None, labels=True, sort=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
| 473,274
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
| 473,275
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
| 473,276
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
| 473,277
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
| 473,278
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
| 473,279
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
| 473,280
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
| 473,281
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``.
| 473,282
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only.
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only.
| 473,283
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only.
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only.
| 473,284
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only.
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only.
| 473,285
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only.
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only.
| 473,286
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only.
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only.
| 473,287
|
def edges_incident(self, vertices=None, labels=True): """ Returns a list of edges incident with any vertex given. If vertices is None, returns a list of all edges in graph. For digraphs, only lists outward edges.
|
def edges_incident(self, vertices=None, labels=True): """ Returns a list of edges incident with any vertex given. If vertices is None, returns a list of all edges in graph. For digraphs, only lists outward edges.
| 473,288
|
def edges_incident(self, vertices=None, labels=True): """ Returns a list of edges incident with any vertex given. If vertices is None, returns a list of all edges in graph. For digraphs, only lists outward edges.
|
def edges_incident(self, vertices=None, labels=True): """ Returns a list of edges incident with any vertex given. If vertices is None, returns a list of all edges in graph. For digraphs, only lists outward edges.
| 473,289
|
def hom(self, im_gens, codomain=None, check=True): """ Homomorphism defined by giving the images of ``self.gens()`` in some fixed fg R-module.
|
def hom(self, im_gens, codomain=None, check=True): """ Homomorphism defined by giving the images of ``self.gens()`` in some fixed fg R-module.
| 473,290
|
def hom(self, im_gens, codomain=None, check=True): """ Homomorphism defined by giving the images of ``self.gens()`` in some fixed fg R-module.
|
def hom(self, im_gens, codomain=None, check=True): """ Homomorphism defined by giving the images of ``self.gens()`` in some fixed fg R-module.
| 473,291
|
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the unique graph on \{0,1,...,n-1\} ( n = self.order() ) which - is isomorphic to self, - is invariant in the isomorphism class.
|
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the unique graph on \{0,1,...,n-1\} ( n = self.order() ) which - is isomorphic to self, - is invariant in the isomorphism class.
| 473,292
|
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the unique graph on \{0,1,...,n-1\} ( n = self.order() ) which - is isomorphic to self, - is invariant in the isomorphism class.
|
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the unique graph on \{0,1,...,n-1\} ( n = self.order() ) which - is isomorphic to self, - is invariant in the isomorphism class.
| 473,293
|
def has_good_reduction(self, P=None): r""" Returns True iff this point has good reduction modulo a prime.
|
def has_good_reduction(self, P=None): r""" Returns True iff this point has good reduction modulo a prime.
| 473,294
|
def has_good_reduction(self, P=None): r""" Returns True iff this point has good reduction modulo a prime.
|
def has_good_reduction(self, P=None): r""" Returns True iff this point has good reduction modulo a prime.
| 473,295
|
def longest_path(self, s=None, t=None, weighted=False, algorithm="MILP", solver=None, verbose=0): r""" Returns a longest path of ``self``.
|
def longest_path(self, s=None, t=None, weighted=False, algorithm="MILP", solver=None, verbose=0): r""" Returns a longest path of ``self``.
| 473,296
|
def longest_path(self, s=None, t=None, weighted=False, algorithm="MILP", solver=None, verbose=0): r""" Returns a longest path of ``self``.
|
def longest_path(self, s=None, t=None, weighted=False, algorithm="MILP", solver=None, verbose=0): r""" Returns a longest path of ``self``.
| 473,297
|
def longest_path(self, s=None, t=None, weighted=False, algorithm="MILP", solver=None, verbose=0): r""" Returns a longest path of ``self``.
|
def longest_path(self, s=None, t=None, weighted=False, algorithm="MILP", solver=None, verbose=0): r""" Returns a longest path of ``self``.
| 473,298
|
def longest_path(self, s=None, t=None, weighted=False, algorithm="MILP", solver=None, verbose=0): r""" Returns a longest path of ``self``.
|
def longest_path(self, s=None, t=None, weighted=False, algorithm="MILP", solver=None, verbose=0): r""" Returns a longest path of ``self``.
| 473,299
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.