Message Boards Message Boards


Use Wolfram|Alpha in Python?

Posted 2 years ago
1 Reply
0 Total Likes

Hi there! I'm developing a program in Python to calculate the energy of a primary cosmic ray particle using the NKG-function. Part of the process involves solving an equation in x in the form ax^1.2 + bx^2.2 + cx^3.2 + dx^4.2 - s = 0, where a, b, c, d and s are known variables.

I've installed the Wolfram Alpha package using pip, and am working in the IDE PyCharm. The code correctly calculates the value of x, but I think it is stored as a string, rather than a float. In order to use this x value in further calculations, I need to convert it into a float. I know how to do this in Python, but was wondering how this is done using the Wolfram Alpha language?

This is the section of the code so far:

client = wf.Client("app_ID") #app_ID is the app id

q = "Solve 274770*x**1.2 + 8271.8*x**2.2 + 79.555*x**3.2 + 0.22184*x**4.2 - 35435557377 = 0"
res = client.query(q)
answer = next(res.results).text

ra1 = answer
print("ra1:", ra1)

ra2 = (k*r0**eta) / (measured_density_a*(h*ra1**0.2 + g*ra1**1.2 + i*ra1**2.2 + e*ra1**3.2))
print("ra2", ra2)

This is the output when I run the code:

x = 385.279
ra1: x = 385.279

Traceback (most recent call last):
  File "C:/Users/Nadia/PycharmProjects/Particle_Energy/energy_code/", line 282, in <module>
    ra2 = (k * r0 ** eta) / (measured_density_a * (h * ra1 ** 0.2 + g * ra1 ** 1.2 + i * ra1 ** 2.2 + e * ra1 ** 3.2))

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

Thank you in advance!

Posted 8 months ago


I think your error here is not related with wolfram.

Python basically says that one of the variables on the left of the ** operator is a string. Try to print ra1 and see if it's numeric, if yes, cast it with float(...) or int(...)

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract