[R] Function Help

Ben Bolker bolker at ufl.edu
Mon Oct 12 03:03:09 CEST 2009




cls59 wrote:
> 
> 
> 
> jimdare wrote:
>> 
>> Hi there,
>> 
>> I have created the function below:
>> 
>> pirate<-function(x){
>> a<-x-1; b<-a/5; c<-a-b;
>> d<-c-1; e<-d/5; f<-d-e;
>> g<-f-1; h<-g/5; i<-g-h;
>> j<-i-1; k<-j/5; l<-j-k;
>> m<-l-1; n<-m/5; o<-m-n;
>> final<-o/5;
>> 
>> final
>> }
>> 
>> I want to run this function until the output ('final') is an exact
>> integer (e.g. 893.00000 rather than 893.78332).  I then need to find out
>> what value of X (input) resulted in this integer.  Could someone please
>> help?  I am relatively inexperienced at creating functions.
>> 
>> Kind regards,
>> James 
>> 
>> 
> 
> 
> You could approach this problem by setting it up as an optimization
> problem where the task is to guess the value of x such that the squared
> difference between pirate(x) and your target value is minimized. The
> difference is squared in order to ensure the optimizer attempts to drive
> the difference to 0 instead of -infinity. A function that calculates the
> squared difference between any function evaluated at a point x and some
> target value is:
> 
> sqDiff <- function( x, funObj, target ){
> 
>   return( ( target - funObj(x) )^2 )
> 
> }
> 
> You can then use R's nlm() function in an attempt to discover the value of
> x that results in your target value of 893. This requires specifying an
> initial guess p:
> 
> nlm( sqDiff, p = 5000, funObj = pirate, target = 893 )
> 
> $minimum
> [1] 1.996023e-07
> 
> $estimate
> [1] 13634.3
> 
> $gradient
> [1] -3.72529e-14
> 
> $code
> [1] 1
> 
> $iterations
> [1] 3
> 
> 
> The solver came up with an estimate of 13634.3 for x:
> 
> pirate( 13634.3 )
> [1] 892.9996
> 
> Achieving a solution that provides the exact value of 893 is very unlikely
> using numerical optimization since these techniques involve refining a
> series of guesses until one of the guesses is "good enough"-- i.e. within
> 1*10^{-6} of your target value-- at which point the algorithm terminates.
> 
> To get an answer that provides the target number of 893 exactly you will
> probably have to use a symbolic  solver-- the Ryacas or rSymPy packages
> provide interfaces to computer algebra systems that may have the necessary
> symbolic tools to help you here.
> 
> Good luck!
> 
> -Charlie
> 


 If you put all of this into Yacas (or Mathematica) you get:

In> Simplify(final)
Out> (4*(256*x-2101))/15625

You can then pick your solution:

In> Solve(z==1,x)
Out> {x==24029/1024}

Then:

pirate(24029/1024) is exactly 1 

In> Solve(z==893,x)
Out> {x==13961529/1024}

pirate(13961529/1024)
is exactly 893

and so forth.


-- 
View this message in context: http://www.nabble.com/Function-Help-tp25848627p25849340.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list