Tuesday, October 13, 2015

Maths Tests With R

This maths problem hit the news recently, about how far a crocodile should swim up the bank before going on land, in order to catch a zebra in the shortest possible time. It appears to be an A-level question, i.e. for 18-year old students.

The first two questions are arithmetic; more about understanding the question being asked. But the main question is obviously calculus: you are supposed to differentiate, and find out where it is zero.

I happened to have R open at the time, and my calculus is a bit rusty on how to differentiate a square root. So, this is what I typed:

T = function(x){
(5 * (36 + x^2) ^ 0.5) + 4 * (20-x)

(curly brackets were optional: it could all have been on one line.)

Then to answer the three questions:

optimize(T, lower=0, upper=20)

I.e. if he swims the whole way it is 10.44 seconds, if he cuts to land immediately it takes 11 seconds, and the 3rd line tells me he should swim 8 metres, then cut to land, and it will take 9.8 seconds.

Or, if you want to see how I should have solved it, and be reminded how to do a tricky differentiation, go to https://www.youtube.com/watch?v=xko48OoTAQU and watch from 5:00 to about 10:00. For comparison, It took me less than 1 minute to write the function and get the solutions. R itself ran instantly, of course.

As a data scientist, the important thing here is I use the same techniques when things get messy. If you show me enough observations of crocodiles catching zebras, I can give you an estimated function that also takes into account the speed of the flowing water, the wind speed, the age of the zebra, the water temperature, the air temperature, the weight of the crocodile, and when he last ate!

No comments: