0

I have a smooth function f(x) = sin(x / 5) * exp(x / 10) + 5 * exp(-x / 2) The task is to explore a non-smooth function h(x) = int(f(x)) on the interval of 1 to 30. In other words, each value of f (x) is converted to type int and the function takes only integer values. I am trying to build h(x) with help of matplotlib.

import math
import numpy as np
from scipy.optimize import minimize
from scipy.linalg import *
import matplotlib.pyplot as plt

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

def h(x):
    return int(f(x))

x = np.arange(1, 30)
y = h(x)

plt.plot(x, y)
plt.show()

The code doesn't work. Running the code raises

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

Using VS I get:

enter image description here

1
  • "The code doesnt work." is not a proper problem description. In this case it's rather easy to guess what the error is, but in general questions without proper problem description are off topic. Here the problem is that your function f returns an array. To convert a numpy array to integer you need array.astype(int). Commented Jun 3, 2017 at 16:46

2 Answers 2

2

int is a Python class which returns a single int instance. To convert a NumPy array of floats to a NumPy array of integers, use astype(int):

import numpy as np
import matplotlib.pyplot as plt

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

def h(x):
    return f(x).astype(int)

x = np.arange(1, 30)
y = h(x)

plt.plot(x, y)
plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!
1

Use rounding down,

def h(x):
    return np.floor(f(x));

or rounding towards zero

def h(x):
    return np.fix(f(x));

instead of the implicit rounding during integer conversion.

Comments

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.