hcp
hcp

Reputation: 347

Python3: TypeError: can't multiply sequence by non-int of type 'float' when ploting a fitted function

I'm trying to plot a function but for some reason it returns me a type error that I can't seem to find. These are the reproducible steps:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

mass = [0.02, 0.05, 0.1, 0.15, 0.2, 0.25]
y = [0.755, 0.725, 0.668, 0.61, 0.55, 0.491]

def y_for_ideal_spring(m, k, y_0):
    a_g = 9.8 #m/s^2
    return np.divide(np.multiply(a_g,m) + np.multiply(k,y_0), k)

def y_for_real_spring_1(m, k, y_0, alpha):
    a_g = 9.8
    return y_0 + np.divide(- k -  np.sqrt(k**2 + np.prod([4, a_g, m, alpha])), np.multiply(2, alpha))

popt_0, pcov_0 = curve_fit(y_for_ideal_spring, mass, y)

popt_1, pcov_1 = curve_fit(y_for_real_spring_1, mass, y, p0 = [popt_0[0], popt_0[1],1])

but when I try to plot I get the following error:

TypeError: can't multiply sequence by non-int of type 'float'

This is how I'm plotting it:

plt.plot(mass, y, 'go')
plt.plot(mass, y_for_ideal_spring(mass, *popt_0), '--r')
plt.plot(mass, y_for_real_spring_1(mass, *popt_1), '--b')

Upvotes: 1

Views: 48

Answers (1)

sotmot
sotmot

Reputation: 1313

This is because mass is of type list. It can be solved by casting it as a numpy array.

mass = np.array([0.02, 0.05, 0.1, 0.15, 0.2, 0.25])
y = np.array([0.755, 0.725, 0.668, 0.61, 0.55, 0.491])

The output albeit with a few warnings from curve_fit: Code output :)1

Upvotes: 1

Related Questions