2015-10-26 HW13

posted Oct 26, 2015, 5:09 AM by Samuel Konstantinovich   [ updated Dec 3, 2015, 7:17 AM ]
Do Now:
Write two scheme functions on paper:
1.
(countEvenPositiveSub L) that takes a list L that has numerical atoms, or lists of numerical atoms. The list can be empty, and have empty sublists. 
The function returns the number of positive even values.
(countEvenPositiveSub '( 1 -2 (-4 4) (5 (6))))


2. 
(isCloseEnough a b)
#true when a and b have a percent difference less than 0.0001
#false otheriwse.

What is the formula for %difference?

Classwork:

Square root approximation!!!
We can use recursion 

We can calculate the square root of a number by:
1. guessing the answer, and checking if we are close enough.
2. If we aren't close enough we can make our guess closer to the right answer and try again.

(sqrt 100)
let us guess 1 as the answer.

n / (sqrt n) should equal (sqrt n)
so:
n / guess = guess    or at least they should be really close.

100/ 1 = 1 
or 
100 = 1 , not very close to our guess so a better guess would be between 1 and 100.

we calculate a better guess in many ways, lets use "average of guess/n and guess" as our better guess

better guess = 50.5

we can check again!

100 / 50.5 = 50.5 
   1.98~  = 50.5 isn't very close

better guess  is (1.98~+50.5) / 2  -> 26.24   even closer. 
Basically 

Calculate the next 2 guesses on paper so you know how this works.



The next 3 guesses:

15.02553
10.84043
10.00005289
...


Homework13:

You need to write:

(isCloseEnough a b)

(betterGuess n guess)

and use them along with this:

(define mySqrt (lambda n)
    (sqrtHelp n 1.0) )   

You are writing the function:

(sqrtHelp n guess)

It is recursive, and will keep trying to guess again until the guess is close enough.

There are only 2 cases:

-your guess is close enough (stop and you are done)

-your guess isn't close enough, so you keep going.














Comments