06-17-2021, 05:13 AM
When I enter the code blow, I check it and get no errors in the HPPL editor. When I try to run it, however, I get a syntax error in line 51. It works in CPython.
Traceback (most recent call last):
File "<stdin>", line 51
SyntaxError: invalid syntax
Traceback (most recent call last):
File "<stdin>", line 51
SyntaxError: invalid syntax
Code:
#PYTHON name
# cubic
from math import *
# compute real or complex roots of cubic polynomial
def cubic( a2, a1, a0 ):
global z1,z2,z3
Q = (3*a1 - a2**2)/9
R = (9*a1*a2 - 27*a0 - 2*a2**3)/54
D = Q**3 + R**2 # polynomial discriminant
if (D >= 0): # complex or duplicate roots
S = sgn(R + sqrt(D))*abs(R + sqrt(D))**(1/3)
T = sgn(R - sqrt(D))*abs(R - sqrt(D))**(1/3)
z1 = -a2/3 + (S + T) # real root
z2 = -a2/3 - (S + T)/2 # real part of complex root
z3 = -a2/3 - (S + T)/2 # real part of complex root
im = abs(sqrt(3)*(S - T)/2) # complex part of root pair
else: # distinct real roots
th = acos(R/sqrt( -Q**3))
z1 = 2*sqrt(-Q)*cos(th/3) - a2/3
z2 = 2*sqrt(-Q)*cos((th + 2*pi)/3) - a2/3
z3 = 2*sqrt(-Q)*cos((th + 4*pi)/3) - a2/3
im = 0
return im # imaginary part
# sign of number
def sgn( x ):
if x < 0.0:
return -1
return 1
print("solve: x^3 + a*x^2 + b*x + c = 0")
a,b,c = input("a,b,c? ").split(",")
a=int(a)
b=int(b)
c=int(c)
im = cubic( a, b, c )
if im != 0.0:
print("{",f"{z1:6.4f}, {z2:6.4f} + {im:6.4f}j, {z3:6.4f} - {im:6.4f}j","}")
else:
print("{",f"{z1:6.4f}, {z2:6.4f}, {z3:6.4f}","}")
#end
EXPORT cubic()
BEGIN
PYTHON(name);
END;