0

I'm a python beginner and I'm trying to solve a cubic equation with two independent variables and one dependent variable. Here is the equation, which I am trying to solve for v:

3pv^3āˆ’(p+8t)v^2+9vāˆ’3=0

If I set p and t as individual values, I can solve the equation with my current code. But what I would like to do is set a single t and solve for a range of p values. I have tried making p an array, but when I run my code, the only return I get is "[]". I believe this is an issue with the way I am trying to print the solutions, i.e. I'm not asking the program to print the solutions as an array, but I'm not sure how to do this.

Here's my code thus far:

# cubic equation for solution to reduced volume 

## define variables ##
# gas: specify

tc = 300
t1 = 315
t = t1/tc

from sympy.solvers import solve
from sympy import Symbol

v = Symbol('v')

import numpy as np
p = np.array(range(10))
print(solve(3*p*(v**3)-(v**2)*(p+8*t)+9*v-3,v))

Any hints on how to get the solutions of v for various p (at constant t) printed out properly?

2 Answers2

1

You can simply use a for loop I think. This is what seems to work:

for p in range(10):
    solution = solve(3*p*(v**3)-(v**2)*(p+8*t)+9*v-3, v)
    print(solution)

Also, note that range(10) goes from 0 to 9 (inclusive)

A.M. Ducu
  • 892
  • 7
  • 19
0

Same idea as previous answer, but I think it's generally good practice to keep imports at the top and to separate equation and solution to separate lines etc. Makes it a bit easier to read

from sympy.solvers import solve
from sympy import Symbol
import numpy as np

tc = 300
t1 = 315
t = t1/tc

v = Symbol('v') # Variable we want to solve
p = np.array(range(10)) # Range of p's to test

for p_i in p: # Loop through each p, call them p_i
  print(f"p = {p_i}")
  equation = 3*p_i*(v**3)-(v**2)*(p_i+8*t)+9*v-3
  solutions = solve(equation,v)
  print(f"v = {solutions}\n")
Sandsten
  • 727
  • 3
  • 16