1

I am trying to solve a system of trigonometric equations and I think Python is not generating the right solution. Equations I am trying to solve:

  • 1 − 2cosθ1 + 2cosθ2 − 2cosθ3 = −0.8

  • 1 − 2cos5θ1 + 2cos5θ2 − 2cos5θ3 = 0

  • 1 − 2cos7θ1 + 2cos7θ2 − 2cos7θ3 = 0

My Python code:

from scipy.optimize import fsolve
import math
import numpy as np

def equations(p):
    x,y,z = p
    f1 = (1 - 2*math.cos(math.radians(x)) + 2*math.cos(math.radians(y)) - 2*math.cos(math.radians(z)) + 0.8)
    f2 = (1 - 2*math.cos(math.radians(5*x)) + 2*math.cos(math.radians(5*y)) - 2*math.cos(math.radians(5*z)))
    f3 = (1 - 2*math.cos(math.radians(7*x)) + 2*math.cos(math.radians(7*y)) - 2*math.cos(math.radians(7*z)))
    return (f1,f2,f3)

x,y,z = fsolve(equations,(0,0,0))

print equations((x,y,z))

This printed:

(-1.9451107391432743e-13, 4.241273998673023e-12, -1.5478729409323932e-12)

which is wrong because I checked it using:

print (1 - 2*math.cos(math.radians(5*-1.9451107391432743e-13)) + 
           2*math.cos(math.radians(5*4.241273998673023e-12)) - 
           2*math.cos(math.radians(5*-1.5478729409323932e-12)))

and this does not print 0 but prints -1. Can anyone please tell me what am I doing wrong here?

Another question is fsolve generates solution based on initial values. So if I change my initial values from (0,0,0) to (1,1,1), I might get another new solution. Is there a way I can define a "range" of initial values for each variablex,y,z` and get a range of solutions?

VP.
  • 15,509
  • 17
  • 91
  • 161
Nikhil Gupta
  • 551
  • 10
  • 28

1 Answers1

2

Your code appears to be fine. It prints the errors at the end, not the solution. You are in fact checking the solution by calling your equations with the answer found by fsolve in the last two lines. if you want to see the values of the variables, you can do print x, y, z.

chthonicdaemon
  • 19,180
  • 2
  • 52
  • 66
  • Another question is `fsolve` generates solution based on initial values. So if I change my initial values from `(0,0,0)` to `(1,1,1), I might get another new solution. Is there a way I can define a "range" of initial values for each variable `x,y,z` and get a range of solutions? Can you please suggest me if there is a way to do it? Thanks again – Nikhil Gupta Oct 06 '14 at 04:29
  • 1
    There is unfortunately no direct way of finding all solutions to nonlinear equations, even if a range of starting values is specified. You can, however, start from a number of different starting points and remember each solution using a `for` loop, something like `solutions = [fsolve(equations, startpoint) for startpoint in [(0, 0, 0), (1, 1, 1)])` – chthonicdaemon Oct 06 '14 at 06:40
  • Just note that you should try and write that program, and if you get stuck, you should ask a new question rather than asking new questions in the comments. – chthonicdaemon Oct 06 '14 at 06:42