Ask Your Question
0

interact with slider

asked 2020-04-04 11:02:19 +0100

ortollj gravatar image

HI

Ubuntu 18.04,Jupyter notebook 9.0

from copy import deepcopy

''' Newton’s method. '''
show(LatexExpr(r"f'(x_n) \, (x-x_n) + f(x_n)"))
show(LatexExpr(r"x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)}"))
print("source :","https://en.wikipedia.org/wiki/Newton%27s_method")
rd=5 # rounding display
def N_f(x_0=0.5,f=x^2,delta=10^(-6),n=0,xL=[]) :
    global rRg,rd
    """real root approximation"""
    fd=f.derivative(x)
    epsilon=abs(f(x_0))
    xnPlus1=0
    xL.append((n,round(x_0,rd)))
    rRg=[]
    if epsilon > delta and n<100 and fd(x_0)!=0:
        n+=1
        xnPlus1=x_0-f(x_0)/fd(x_0)
        print('x_'+str(n)+' : ',round(x_0,rd),'\t x_'+str(n+1),' : ',round(xnPlus1,rd),
              ' epsilon : ',round(epsilon,rd),' delta : ',round(delta,rd))
        #xL.append((n,xnPlus1))

        return N_f(xnPlus1,f,delta,n,xL)
    else:
        return x_0,n+1,delta,xL


'''test of function N_f '''

#R.<x> = PolynomialRing(RR)
f=x^3 - 2*x^2 + x - 1

for r in f.roots():
    #show(r)
    if r[0].imag_part()==0 :
        realRoot=r[0]
        show("real root: ",r[0])
        show("real root numerical value:\t",r[0].n())

G = plot(f, (x, -1/2, 2), thickness=2, color='green', title="f(x)")
Gp0=point((realRoot,0),color='red',size=40)
Gt0 = text(r"$%s $" %(latex(f)),(0.75,1),color='green')
Gt1 = text(r"$%s $" %(latex(round(realRoot,rd))),(realRoot*(1+1/8),0.1),color='red')
Gl0=line([(0,realRoot), (2*realRoot,realRoot)],color='blue')

f_Coeffs=f.coefficients(sparse=False)
try: deltag
except NameError: deltag = None
if deltag ==None :
    deltag= 5*10^(-2)

try: x_0g
except NameError: x_0g = None
if x_0g ==None :
    x_0g=(realRoot-1/2).n()

#print(' \t \t delta : ',round(delta,rd))
GG=G+Gp0+Gl0+Gt0+Gt1
nbColorMaxg=16
rainbowG=rainbow(nbColorMaxg, 'rgbtuple')

try: colorNg
except NameError: colorNg = None
if colorNg ==None :
    colorNg= 0

try: newtonG
except NameError: newtonG = None
if newtonG ==None :
    newtonG= Graphics()

try: rRg
except NameError: rRg = None
if rRg ==None :
    rRg=[]

@interact
#def _(x_0=input_box(round(x_0g,rd), width=20, label="x_0=")):
def _( deltal=slider(0.0001,0.5,0.0001,0.3)):

    global GG,newtonG,delta,x_0g,colorNg,f,nbColorMaxg,realRoot,rRg
    deltag=deltal;
    if rRg != [] :
        rRg=[]
    rRg=N_f(x_0=x_0g,f=f,delta=deltag)
    newtonG= GG
    if rRg[3] !=[] :
        newtonG=list_plot(rRg[3],color=rainbowG[colorNg % (nbColorMaxg-1) ],size=40)
        colorNg+=1

    (GG+newtonG).show()
    #show(rRg[3])

Q1) How to supress warning messages: SageMath/local/lib/python3.7/site-packages/sage/repl/ipython_kernel/__main__.py:85: DeprecationWarning: Substitution using function-call syntax and unnamed arguments is deprecated and will be removed from a future release of Sage; you can use named arguments instead, like EXPR (x = ..., y = …) See http://trac.sagemath.org/5930 for details.

Q2) why do the values of the convergence curves accumulate in rRg [3]?. At the initialization we read in rRg:

[1.81956500676553,
 4,
 0.300000000000000,
 [(0, 1.25488), (1, 2.55835), (2, 2.05721), (3, 1.81957)]]

Then after having positioned the cursor on the far left we read in rRg:

[1.75489290022857,
 6,
 0.000100000000000000,
 [(0, 1.25488),
  (1, 2.55835),
  (2, 2.05721),
  (3, 1.81957),
  (0, 1.25488),
  (1, 2.55835),
  (2, 2.05721),
  (3, 1.81957),
  (0, 1.25488),
  (1, 2.55835),
  (2, 2.05721),
  (3, 1.81957),
  (4, 1.75876),
  (0, 1.25488),
  (1, 2.55835),
  (2, 2.05721),
  (3, 1.81957),
  (4, 1.75876),
  (5, 1.75489)]]

despite I clear rRg:

if rRg != [] :
    rRg=[]

do a list(rRg) in the next cell and run it

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
0

answered 2020-04-04 15:13:19 +0100

dsejas gravatar image

updated 2020-04-04 20:38:39 +0100

Hello, @ortollj! Let's answer your questions:

  1. How to supress warning messages? The problem is your definition of the function f (line 31 of your code). Instead of writing

    f = x^3 - 2*x^2 + x - 1
    

    you should write

    f(x) = x^3 - 2*x^2 + x - 1
    

    That's it! Notwithstanding the fact that this seems to be an unimportant addition to the code, it is actually a necessary, for Sage needs to know the independent variable(s) of a function in order to make some operations, like the derivative, etc.

  2. Why do the values of the convergence curves accumulate in rRg[3]? I think you just discovered a bug. I don't know if this is Sage bug or a Jupyter bug, so I am posting a related question. It seems that the list xL is being kept in memory from execution to execution of the interact. For example, if you uncomment your last line of code and execute the interact, you will notice that every time you move the slider, the list rRg[3], which comes from xL in your first subroutine, gets bigger and bigger. It is storing the convergent sequences for every deltal you use (i.e., one sequence for every position of the slider you use).

    So, what do to do? I was able to solve this problem by changing your line number 85 from

    rRg=N_f(x_0=x_0g,f=f,delta=deltag)
    

    to the almost similar

    rRg=N_f(x_0=x_0g,f=f,delta=deltag,xL=[])
    

    That way, you force xL to become empty on every movement of the slider, so the information from previous executions (the previous convergent sequence for the previous slider position) is forgotten, and you get only the information for the current position of the slider.

I hope this helps!

edit flag offensive delete link more

Comments

Thank you @dsejas for Q1 it is ok now with what you recommand ,f(x), no more warning. my Q2 was about why there are many sequences in rRg[3] ? it should have been only

[(0, 1.25488),
  (1, 2.55835),
  (2, 2.05721),
  (3, 1.81957),
  (4, 1.75876),
  (5, 1.75489)]
ortollj gravatar imageortollj ( 2020-04-04 17:22:26 +0100 )edit

Hello, @ortollj! Sorry about the confusion; I didn't sleep much last night, so I didn't understand clearly your question. I am updating my answer to solve your Q2.

dsejas gravatar imagedsejas ( 2020-04-04 19:55:19 +0100 )edit
1

Oh, by the way, during the experiments I run to find the problem, I was able to simplify part of your code. I hop you don't mind. If it's of any help to you, feel free to modify and/or adapt it to your needs. You can find it here. In particular, I recommend NOT to use global variables.

dsejas gravatar imagedsejas ( 2020-04-04 20:16:59 +0100 )edit

thank you very much @dsejas finally I unnecessarily complicated things ;-(.

your modifications on sageCell

one debian pastezone , tabulations are bad.

ortollj gravatar imageortollj ( 2020-04-04 21:30:54 +0100 )edit

Thank you, @ortollj for uploading the code to SageCell. I didn't post it that way, because the permalink was too large for the allowed number of characters in comments.

dsejas gravatar imagedsejas ( 2020-04-04 22:36:01 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2020-04-04 11:02:19 +0100

Seen: 487 times

Last updated: Apr 04 '20