0

I have an equation which contains lots of variables.

enter image description here

I am trying to get derivatives of this equation. I tried "Sympy 1.7"

This is my code:

import cmath
from cmath import pi
from sympy import *

kx, ky, λ, n1 = symbols('kx, ky, λ, n1')
init_printing(use_unicode=True)


def kz1(kx, ky, λ, n1):
    return cmath.sqrt((n1 ** 2) * ((2 * pi / λ) ** 2) - ((cmath.sqrt(kx ** 2 + ky ** 2)) ** 2))

diff(kz1(kx, ky, λ, n1), kx)

I was expecting I'll get an equation composed with variables in the original equation. But I kept getting error like this:

Traceback (most recent call last):
  File "/Users/......./venv/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3417, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-c3e2605acdaa>", line 12, in <module>
    diff(kz1(kx, ky, λ, n1), kx)
  File "<ipython-input-2-c3e2605acdaa>", line 10, in kz1
    return cmath.sqrt((n1 ** 2) * ((2 * pi / λ) ** 2) - ((cmath.sqrt(kx ** 2 + ky ** 2)) ** 2))
  File "/Users/....../venv/lib/python3.8/site-packages/sympy/core/expr.py", line 355, in __complex__
    return complex(float(re), float(im))
  File "/Users/....../venv/lib/python3.8/site-packages/sympy/core/expr.py", line 350, in __float__
    raise TypeError("can't convert expression to float")
TypeError: can't convert expression to float

Why it seems like the Sympy want to show the result in the form of float instead of an equation?

Joanne
  • 503
  • 1
  • 3
  • 15
  • 1
    Does this answer your question? [TypeError: can't convert expression to float](https://stackoverflow.com/questions/22555056/typeerror-cant-convert-expression-to-float) – shimo Dec 05 '20 at 21:12

1 Answers1

3

You're mixing libraries. If you want to operate purely symbolic, you have to express it all as sympy like so:

import sympy as sp

kx, ky, λ, n1 = sp.symbols('kx, ky, λ, n1')


def kz1(kx, ky, λ, n1):
    return sp.sqrt((n1 ** 2) * ((2 * sp.pi / λ) ** 2) - ((sp.sqrt(kx ** 2 + ky ** 2)) ** 2))

sp.diff(kz1(kx, ky, λ, n1), kx)
Stefan
  • 897
  • 4
  • 13