Suppose I have function, that accepts list of arguments. List can be of variable length and function is ok with it. For example:
import math
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
%matplotlib inline
def PlotSuperposition(weights):
def f(x):
y = 0
for i, weight in enumerate(weights):
if i==0:
y+=weight
else:
y += weight*math.sin(x*i)
return y
vf = np.vectorize(f)
xx = np.arange(0,6,0.1)
plt.plot(xx, vf(xx))
plt.gca().set_ylim(-5,5)
PlotSuperposition([1,1,2])
shows
I can hardcode interact for given number of arguments, like here
interact(lambda w0, w1, w2: PlotSuperposition([w0,w1,w2]), w0=(-3,+3,0.1), w1=(-3,+3,0.1), w2=(-3,+3,0.1))
which shows
But how can I make number of sliders defined programmatically?
I tried
n_weights=10
weight_sliders = [widgets.FloatSlider(
value=0,
min=-10.0,
max=10.0,
step=0.1,
description='w%d' % i,
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='.1f',
) for i in range(n_weights)]
interact(PlotSuperposition, weights=weight_sliders)
but got error
TypeError: 'FloatSlider' object is not iterable
inside PlotSuperposition saying that interact doesn't pass a list of values to the function.
How to accomplish?


