## WeBWorK Problems

### Q: list of lists ### Q: list of lists

by Dick Lane -
Number of replies: 1
Consider applying Newton's method to approximate zeros of f(x) = b + x cos(x) for various values of b. Some choices of x_0 yield convergence to a nearby zero of f while others have different results (which are worth discussing during a class).

I would like to choose a random value of b and then present a random choice from those starts which converge to a nearby zero. E.g., if b = 1, then have x0 = list_random(2,4,5,8,11) but if b = 3, then have x0 = list_random(3,4,8,11). That type of casewise processing can be done in Perl, but I would prefer a more elegant (and extensible) approach. With several other languages (Lisp, Maple, Python) I could do something resembling
@B = ( 1 , 2 , 3 ) ;
@X = ( (2,4,5,8,11) , (2,3,4,5,8,11) , (3,4,8,11) ) ;
$j = random(0,2,1) ; ## is random( 0 , @B , 1 ) an alternative?$b = $B[$j ] ;
$x0 = list_random($X[ $j ] ) ; [Note: @BX = ( (b,list) , ( 1 , (2,4,5,8,11) ) , ( 3 , (3,4,8,11) ) ) would be easier to maintain --- at the price of an extra level of indexing.] In any event, I will welcome suggestions about Perl/PG programming because all of my current attempts at a non-kludge version have failed. Note: http://webwork.maa.org/moodle/mod/forum/discuss.php?d=2272 discusses some related stuff about lists, but I have not yet been able to apply it here. In reply to Dick Lane ### Re: Q: list of lists by Gavin LaRose - Hi Dick, You can do the same sort of nested data in Perl and therefore in problems. The following should be something that would work. @BX = ( [ 1, [2,4,5,8,11] ], [ 2, [2,3,4,5,8,11] ], [ 3, [3,4,8,11] ] );$j = random( 0, scalar(@BX), 1 );
$b =$BX[$j]->;$x0 = $BX[$j]->;

Now $x0 is a list reference. Thus if$j is 0, @$x0 is the list (2,4,5,8,11) and we can dereference elements of the list with the arrow operator:$x0-> is 5.

Does that help?
Gavin