0

I have a func

f(x) = sin(x/5.0)*exp(x/10.0) + 5*exp(-x/2.0)

I need to solve system of linear equations

w0 + w1x1 + w2(x1)**2 + ... + wn(x1)**n = f(x1)

I solve that but I have a problem with plot it

from math import sin, exp
from scipy import linalg
import numpy as np

b = []
def f(x):
    return sin(x/5.0)*exp(x/10.0) + 5*exp(-x/2.0)

for i in [1, 15]:
    b.append(f(i))

A = []

for i in [1, 15]:
    ij = []
    x0 = i ** 0
    x1 = i ** 1
    ij.append(x0)
    ij.append(x1)
    A.append(ij)

matrix = np.array(A)
b = np.array(b).T

x = linalg.solve(matrix, b)
from matplotlib import pyplot as plt
plt.plot(x, f(x))

But it returns

TypeError: only length-1 arrays can be converted to Python scalars

How can I solve this problem?

1 Answer 1

3

math.sin and math.exp expect scalar inputs. If you pass an array, you get a TypeError

In [34]: x
Out[34]: array([ 3.43914511, -0.18692825])

In [35]: math.sin(x)
TypeError: only length-1 arrays can be converted to Python scalars

from math import sin, exp loads sin and exp from the math module and defines them as functions in the global namespace. So f(x) is calling math's version of the sin function on x which is a NumPy array:

def f(x):
    return sin(x/5.0)*exp(x/10.0) + 5*exp(-x/2.0)

To fix the error, use NumPy's sin and exp functions instead.

import numpy as np
def f(x):
    return np.sin(x/5.0)*np.exp(x/10.0) + 5*np.exp(-x/2.0)
Sign up to request clarification or add additional context in comments.

2 Comments

Why does it happen?
The functions in the math module from the standard library expects scalars as inputs. The equivalent NumPy functions are designed to work with NumPy arrays. x is a NumPy array, so you need to use np.sin(x), not math.sin(x).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.