0

I want to solve p for Vo using sympy solve, an algorithm that solves an equation without an initial value. Then, I want to find the derivative of p for Vo using TensorFlow's automatic differentiation. I wrote the code below, and the value was calculated well. However, it could not be converted to tensorflow dtype at the end. Is there a way to use TensorFlow tensors compatible with sympy?

from sympy import solve, Symbol, re
import tensorflow as tf`

class Concentrate_calculator:
    def __init__(self, k, k1, m):
        self.k=k
        self.k1=k1
        self.m=m
    
    def calp(self, Vo):
        p=Symbol('p')
        equation = k1*m/(p+k1)+k/p-2*Vo-p
        solution = solve(equation, p)
        p=float(re(solution[2]))
        return p


k=10.0**15
k1=10.0**9.5
m=10.0**19.2    

cal = Concentrate_calculator(k,k1,m)

Vo = tf.Variable(1e18)
#Vo=1e18
with tf.GradientTape() as t:
    t.watch(Vo)
    p=cal.calp(Vo)
  
dpdVo = t.gradient(p,Vo)
print(dpdVo)

TypeError: Cannot convert value 21897084140.095097 to a TensorFlow DType.

  • No, you cannot combine SymPy and TensorFlow. You can however look at the symbolic result of your equation (using symbolic variables for `k`, `k1`, `m` and `Vo`) and implement the result with TensorFlow operations. Or, since in the end it is a cubic equation, you can rearrange it into the form `a*p^3+b*p^2+c*p+d=0` (I think it would boil down to `p^3 + (-2 * Vo + k1) * p^2 + (k1 * m + k - 2 * Vo * k1) * p + (k * k1) = 0`, but you should check that, or use SymPy to do it for you), and use the [cubic formula](https://math.vanderbilt.edu/schectex/courses/cubic/) to solve it. – jdehesa Oct 05 '20 at 15:57
  • You can use lambidfy with tensorflow. I don't know if this is a demo problem or if it is the actual problem that you want to solve but you would be better off not bothering with tensorflow for and just using sympy for this example. – Oscar Benjamin Oct 05 '20 at 17:13
  • thank you for the reply. I'll find another way to abandon sympy. – Yang Jeong Park Oct 06 '20 at 21:54

0 Answers0