2017-11-03 7 views
2

인수 목록을 허용하는 함수가 있다고 가정합니다. 목록은 가변 길이 일 수 있으며 기능은 정상입니다. 예를 들어 :상호 작용 인수를 프로그래밍 방식으로 설정하는 방법은 무엇입니까?

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]) 

enter image description 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)) 

enter image description here

을 보여주는 것처럼, 인수 주어진 수의 상호 작용 하드 코딩 할 수 있습니다 보여줍니다

그러나 프로그래밍 방식으로 정의 된 슬라이더의 수를 어떻게 만들 수 있습니까?

나는
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) 

을 시도했지만 그 상호 작용이 함수에 값 목록을 통과하지 못한 말 PlotSuperposition 내부 오류

TypeError: 'FloatSlider' object is not iterable 

을 얻었다.

수행 방법?

답변

2

첫째, 대신 일반 목록의 키워드 인수의 임의의 수를 취할 함수를 수정 : kwargs 앞에

def PlotSuperposition(**kwargs): 
    def f(x): 
     y = 0 
     for i, weight in enumerate(kwargs.values()): 
      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) 

공지 별표를.

kwargs = {'w{}'.format(i):slider for i, slider in enumerate(weight_sliders)} 

interact(PlotSuperposition, **kwargs) 

enter image description here

: 그런 다음 키/값 인자의 사전에 interact 전화
관련 문제