unsupported operand type(s) error - python-2.7

a = 3,3 b = 5,3
a2 = a**2
b2 = b**2
eq1_sum = a2 + 2ab + b2
eq2_sum = a2 - 2ab + b2
eq1_pow = (a + b)**2
eq2_pow = (a - b)**2
print ’First equation: %g = %g’, % (eq1_sum, eq1_pow)
print ’Second equation: %h = %h’, % (eq2_pow, eq2_pow)
This program it shows error:
TypeError: unsupported operand type(s) for ** or pow(): 'tuple' and 'int'

You need to use . if you wish to use a floating-point number:
a = 3.3
b = 5.3
a2 = a**2
b2 = b**2
Otherwise, using a comma, you're creating a tuple:
>>> a = 3,3
>>> type(a)
<type 'tuple'>
>>> a = 3.3
>>> type(a)
<type 'float'>
You're now getting an error because a and b are tuples and you can't raise tuples to a power.

Related

Sympy tensorproduct and tensorcontraction

I want to do two computations with sympy and one substitution:
The first is: "E:E" or in index notation "E_{ij}E{ji}"
The second is: "T_{ijmn} T_{mnkl}"
After I do these calculations I would like to replace the symbols with numeric values.
I have the following code:
import sympy as sp
import numpy as np
sp.init_printing(pretty_print=False)
# e = sp.MatrixSymbol('e',3,3)
# E = sp.Matrix(e)
def foo():
e = sp.MatrixSymbol('e',3,3)
E = sp.Matrix(e)
result1 = sp.tensorcontraction( sp.tensorproduct(E, E), (0, 2), (1,3))
T = sp.tensorproduct(E, E)
result2 = sp.tensorcontraction( sp.tensorproduct(T, T), (2,4), (3,5))
return [result1, result2]
# Verification
res1, res2 = foo()
E_num = np.array([[1,2,3],
[4,5,6],
[7,8,12]])
res1 = res1.subs({ E[0,0]:E_num[0,0], E[0,1]:E_num[0,1], E[0,2]:E_num[0,2],
E[1,0]:E_num[1,0], E[1,1]:E_num[1,1], E[1,2]:E_num[1,2],
E[2,0]:E_num[2,0], E[2,1]:E_num[2,1], E[2,2]:E_num[2,2]})
res2 = res2.subs({ E[0,0]:E_num[0,0], E[0,1]:E_num[0,1], E[0,2]:E_num[0,2],
E[1,0]:E_num[1,0], E[1,1]:E_num[1,1], E[1,2]:E_num[1,2],
E[2,0]:E_num[2,0], E[2,1]:E_num[2,1], E[2,2]:E_num[2,2]})
check1 = np.einsum("ij,ji", E_num, E_num) - res1
T1 = np.einsum("ij,mn->ijmn", E_num, E_num)
T2 = np.einsum("mn,kl->mnkl", E_num, E_num)
check2 = np.einsum("ijmn,mnkl->ijkl", T1,T2) - res2
In the above code I cannot replace the E matrix with numerical values as the symbolic variable is defined inside the function. I can do it if I define them outside. Any way to look into the expression and get the symbols to replace?
Additionally, check1 is not zero as it appears to be doing E_{ij}E_{ij}, whilst check2 appears to be correct. Am I not asking to contract the correct indices?
Best Regards
Your res1 - before numeric substitute is
In [18]: res1
Out[18]:
2 2 2 2 2 2 2 2 2
e₀₀ + e₀₁ + e₀₂ + e₁₀ + e₁₁ + e₁₂ + e₂₀ + e₂₁ + e₂₂
That's the same as
np.einsum('ij,ij', E_num, E_num)
or
np.sum(E_num * E_num)
The einsum contraction of the array with its transpose:
In [18]: np.einsum("ij,ji", E_num, E_num)
Out[18]: 324
In [19]: np.einsum("ij,ij", E_num, E_num.T)
Out[19]: 324
Using E.T in your res1 calcultion gets the same thing
In [24]: sp.tensorcontraction( sp.tensorproduct(E, E.T), (0, 2), (1,3))
Out[24]:
2 2 2
e₀₀ + 2⋅e₀₁⋅e₁₀ + 2⋅e₀₂⋅e₂₀ + e₁₁ + 2⋅e₁₂⋅e₂₁ + e₂₂
In [25]: _.subs({ E[0,0]:E_num[0,0], E[0,1]:E_num[0,1], E[0,2]:E_num[0,2],
...: E[1,0]:E_num[1,0], E[1,1]:E_num[1,1], E[1,2]:E_num[1,2],
...: E[2,0]:E_num[2,0], E[2,1]:E_num[2,1], E[2,2]:E_num[2,2]})
Out[25]: 324
I haven't read the docs for tensorproduct or tensorcontraction.

I want diophantine convert t_0 ---> n

I want diophantine convert (t_0 ---> n)
from sympy import *
var('x y t_0 n')
def myDiophantine(myf):
myf_diox = list(diophantine(myf))[0][0]
myf_dioy = list(diophantine(myf))[0][1]
print("#1#",type(myf_diox),myf_diox)
myf_diox = myf_diox.subs({t_0:n})
print("#2#",type(myf_diox),myf_diox)
return myf_diox,myf_dioy
myf=5**4*x-2**4*y-1
print("#3#",myDiophantine(myf))
var('z')
print("#4#",type(myf),myf)
print("#5#",type(myf.subs({x:z})),myf.subs({x:z}))
#1# <class 'sympy.core.add.Add'> 16*t_0 + 1
#2# <class 'sympy.core.add.Add'> 16*t_0 + 1
#3# (16*t_0 + 1, 625*t_0 + 39)
#4# <class 'sympy.core.add.Add'> 625*x - 16*y - 1
#5# <class 'sympy.core.add.Add'> -16*y + 625*z - 1
i used subs? It could not be replaced.
Is there a better way?
i want
#2# <class 'sympy.core.add.Add'> 16*n + 1
ref
I want function convert from xy to cells
20220401
from sympy import *
var('x y t_0 n')
def myDiophantine(myf):
d=diophantine(myf)
params = Tuple(*d).free_symbols - myf.free_symbols;
d=Tuple(*d).xreplace(dict(zip(params, [n])))
myf_diox = list(d)[0][0]
myf_dioy = list(d)[0][1]
return myf_diox,myf_dioy
myf=5**4*x-2**4*y-1
myg=myDiophantine(myf)
print("#",myg[0],myg[1])
# 16*n + 1 625*n + 39
https://www.wolframalpha.com/input?i=5%5E4*x-2%5E4*y%3D1
5^4x-2^4y=1
Integer solution
x = 16 n + 1, y = 625 n + 39, n element Z
>>> myf = 5**4*x-2**4*y-1
>>> d = diophantine(myf)
Get a list of parameters that were used for the solution (converting set-of-tuples solution to Tuple-of-Tuples):
>>> params = Tuple(*d).free_symbols - myf.free_symbols; params
{t_0}
Create a replacement dictionary with desired replacements
>>> Tuple(*d).xreplace(dict(zip(params, [n])))
((16*n + 1, 625*n + 39),)
Why didn't your approach work?
>>> Symbol('t_0') in params
False
>>> Symbol('t_0',integer=True) in params
True
Symbols are matched based on name and assumptions, not name alone.
As to getting smaller coefficients for Diophantine equations: this is a known issue.

Collecting sub-expressions of a multivariate polynomial function in Sympy

I have a degree 6 multivariate equation in x and y written in Sympy, e.g.
eqn = a*x**6 + b*x**5*y + c*x**4*y + d*x**3*y + e*x**3*y**2 + ...
Is there a way to collect (x**2+y**2) and rearrange them into the following format?
eqn2 = A*(x**2+y**2)**3 + B*(x**2+y**2)**2 + C*(x**2+y**2) + D
A, B, C, D can be in x, y.
So far I have only tried collect(eqn, x**2 + y**2) and it returned the original equation.
Thank you!
Consider using a temporary symbol z = x**2 + y**2 and replace x**2 with z - y**2, then expand and restore:
>>> ex
A*x**6 + 3*A*x**4*y**2 + 3*A*x**2*y**4 + A*y**6 + B*x**4 + 2*B*x**2*y**2 +
B*y**4 + C*x**2 + C*y**2 + D
>>> ex.subs(x**2, z - y**2).expand().subs(z, x**2 + y**2)
A*(x**2 + y**2)**3 + B*(x**2 + y**2)**2 + C*(x**2 + y**2) + D
Although that works, perhaps a more direct thing to do is separate the expression by coefficients A-D and then factor those collections of terms:
def separatevars_additively(expr, symbols=[]):
free = set(symbols) or expr.free_symbols
d = {}
while free:
f = free.pop()
expr, dep = expr.as_independent(f, as_Add=True)
if dep.has(*free):
return None
d[f] = dep
if expr:
d[0] = expr
return d
>>> coeff = var("A:D")
>>> separatevars_additively(ex, coeff)
{B: B*x**4 + 2*B*x**2*y**2 + B*y**4, A: A*x**6 + 3*A*x**4*y**2 + 3*A*x**2*y**4 + A*y**6, D: D, C: C*x**2 + C*y**2}
>>> Add(*[factor(i) for i in _.values()])
A*(x**2 + y**2)**3 + B*(x**2 + y**2)**2 + C*(x**2 + y**2) + D

Unsupported operand type(s) for +: 'Symbol' and 'str' when forming a string with the factors of a number

I get this error.
What am I doing wrong with the macro?
from sympy import *
var('y')
x=10
d=factorint(x)
print(d)
for k, v in d.items():
y=y+str(k)+'^' +str(v)
print(y)
# {2: 1, 5: 1}
# Traceback (most recent call last):
# File "C:/xxx/.PyCharmCE2018.2/config/scratches/soinsuu.py", line 9, in <module>
# y=y+str(k)+'^' +str(v)
# TypeError: unsupported operand type(s) for +: 'Symbol' and 'str'
#
# Process finished with exit code 1
i want
10=2^1+5^1
10=2**1+5**1
var('y') is equivalent to y = symbols('y'), so y is a symbol. Then you do y+str(k), adding a symbol and a string. That's a type error.
The type of y should be a string. And you want that string to begin with 10=, so initialize it with that:
from sympy import *
x = 10
y = str(x) + '='
d = factorint(x)
print(d)
for k, v in d.items():
y = y + str(k)+'^' +str(v)
print(y)
That said, you are missing the arithmetic operation... and it should be *, not +. 10 is definitely not equal to the sum of 2 and 5.
Also, Python has join string method for this purpose. Use it instead of a loop:
from sympy import *
x = 10
d = factorint(x)
y = str(x) + '=' + '*'.join([str(k)+'^' +str(v) for k, v in d.items()])
print(y)
def Myfactorint(x):
return '+'.join([str(k)+'^' +str(v) for k, v in factorint(x).items()])
from sympy import *
x=10
print(x,'=', factorint(x))
print(x,'=',Myfactorint(x))
# 10 = {2: 1, 5: 1}
# 10 = 2^1+5^1

TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

I am completely new to python and am having some trouble getting to grips with this stuff. I keep getting the aforementioned error message corresponding to line 14 and onwards (starting with p=) in the code below. Any help will be much appreciated. Thank you!
file = open('random.txt','r')
lines = file.readlines()
file.close()
import pandas
colnames = ['x', 'y', 'e']
data = pandas.read_sv('random.txt', names=colnames)
x = data.x.tolist()
y = data.x.tolist()
e = data.x.tolist()
p = [sum(1/int(a**2) for a in e)]
q = [sum(b/int(a**2) for b, a in zip(x, e))]
r = [sum(c/int(a**2) for c, a in zip(y, e))]
s = [sum(b**2/int(a**2) for b, a in zip(x, e))]
t = [sum(b*c/int(a**2) for c, b, a in zip(y, x, e))]
delta = p*s - q**2
a = (r*s - q*t)/delta
b = (p*t - q*r)/delta
import math
Ua = math.sqrt(s/delta)
Ub = math.sqrt(p/delta)
print('a', 'b', 'Ua', 'Ub')
It seems like data.x.tolist() returns a list of strings. You must cast each item to float or int before doing mathematical operations:
x = [float(a) for a in data.x.tolist()]
y = [float(a) for a in data.x.tolist()]
e = [float(a) for a in data.x.tolist()]
Hope it helps.