how do I check when f(x) and g(x) have the same value?

Viewed 84

I want to check when f(x**2+4*x-7) and g(x+5) have the same value and print the x value. Here is the code I have made so far.

def f(x):
    return x**2+4*x−7
def g(x):
    x+5
2 Answers

If you don't want to do it with pen and paper (or you have a more complicated set of equations), you probably want scipy.optimize for root finding and optimization.

from scipy.optimize import minimize_scalar

def f(x):
    return x**2+4*x-7

def g(x):
    return x+5
#this has a abs() so we get close to 0
def z(x):
    return abs(f(x) - g(x))

minimize_scalar(z)

     fun: 7.328129836281505e-08
    nfev: 30
     nit: 25
 success: True
       x: 2.27491722734172

Here is my answer.

from sympy import Eq, solve
from sympy.abc import x

def f(x):
    return x**2+4*x-7

def g(x):
    return x+5

eq1 = Eq(f(x), g(x))

result = solve(eq1, x)
print(result)

Here is the result.

[-3/2 + sqrt(57)/2, -sqrt(57)/2 - 3/2]
Related