Bogus math with app scripts - google-apps-script

Anyone had an issue with bogus math results when using Google Apps Script? The following is the code, where a/b/c are send from another function. A/b/c are verified with the logger. ? StartPt is fine, but endpt is generating a false value.
function calcTime(a,b,c) {
var x;
var startHr = 8;
var startMin = 0;
var startSec=0;
var startPt;
var endPt;
startPt = (startHr * 60) + startMin + (startSec/60);
endPt = (a * 60) + b + (c/60);
Logger.log(endPt);
x = endPt -startPt;
return x;
}
flag
I found that the math error is a multiplication factor of 100 (when endPt is calculated, it multiplies the result by 100). What could cause this?

Real number arithmetic is prone to rounding errors in javascript and apps-script. See Is floating point math broken?. If you're watching your function in the debugger, you'll see rounding errors esp. with (c/60). But that's not likely causing a factor-of-100 error.
Most likely, your parameters aren't what you thing they are. If b arrives as a string, for instance, the calculation of (a * 60) + b + (c/60) will effectively ignore b. The other two parameters, however, will get changed to numbers to to complete the multiplication and division operations. (You can avoid that by using b * 1.)
Anyway, to confirm what you're getting as parameters, try replacing the first few lines of your function with this:
function calcTime(a,b,c) {
var params = {
a:{type:typeof a, value:a},
b:{type:typeof b, value:b},
c:{type:typeof c, value:c}}
Logger.log(params);
var x;
...
Verify that you're getting what you need. If any of the parameters are arriving as date objects, for instance, your math will be wildly incorrect. You may just need to enforce types for your data source.

Related

Applying a function to multiple rows of a data frame where the row is an argument in the function in R

Apologies for the rather long name, but I wanted to be specific. I am rather new to R and coding so please go easy on me.
I have a function as follows:
myfun = function(x, y, g) {return(1 / (1 + exp(y*g%*%x)))}
where x is any data frame with n rows and d columns, y is a scalar and integer, and g is a vector of length d (i.e. same as x). I want to run this function for each row of x without using loops.
I have tried various function in the apply family similar to the code below:
apply(x = a, 1, myfun(y = 1, g = b)
where a is a 3x3 data frame and b is a vector 3 elements long. The above code gives an error that I am missing an argument from myfun, but I am obviously clueless on what to try.
Thanks for any help in advance!
Edit: My actual data frame is huge, sparse, and not very straight forward (I think), so I will include an example data frame and other variables:
a = data.frame(c1 = seq(1,3,1), c2 = seq(4,6,1), c3 = seq(7,9,1))
b = c(1,2,3)
c = 1
Also, I think I may have not clearly stated an important piece of information. I want to actually do a summation of myfun over all the rows and values of b, so I actually want the following:
answer = myfun(a[1,], c, b[1]) + myfun(a[2,], c, b[2]) + myfun(a[3,], c, b[3])
In other words, a[1,] should be applied to myfun with b[1] as they are grouped together. I also made an edit to the function above because I forgot to include return(). Hopefully, this makes things more clear. Apologies for the confusion!

in SAS proc fcmp how to get 2 numbers returned

I have a function that should return 2 numbers (geographic coordinates).
Is it possible to get the function to return 2 numbers?
Here is my function (I need to return x and Y)
proc fcmp outlib=common.functions.geo;
function latlng2lambert72(lat,lng);
LongRef = 0.076042943;
bLamb = 6378388 * (1 - (1 / 297));
aCarre = 6378388 ** 2;
eCarre = (aCarre - bLamb ** 2) / aCarre;
KLamb = 11565915.812935;
nLamb = 0.7716421928;
eLamb = sqrt(eCarre);
eSur2 = eLamb / 2;
*conversion to radians;
lat_rad = (constant("pi") / 180) * lat;
lng_rad = (constant("pi") / 180) * lng;
eSinLatitude = eLamb * sin(lat_rad);
TanZDemi = (tan((constant("pi") / 4) - (lat_rad / 2))) *
(((1 + (eSinLatitude)) / (1 - (eSinLatitude))) ** (eSur2));
RLamb = KLamb * ((TanZDemi) ** nLamb);
Teta = nLamb * (lng_rad - LongRef);
x = 150000 + 0.01256 + RLamb * sin(Teta - 0.000142043);
y = 5400000 + 88.4378 - RLamb * cos(Teta - 0.000142043);
*put x y ;
return (x);
*return (x*1000000000000 + y);
*return (x||'_'||y);
endsub;
quit;
data test;
lat = 50.817500;
lng = 4.374400;
x = latlng2lambert72(lat,lng);
run;
I guess not but then the only option I see would be to make 2 functions and have one return the 1st number and the other return the 2nd number. These 2 functions would be 99% identical and I don't like to duplicate code. Is there a more efficient way to achieve this?
(I don't really understand how subroutines work. Could they be used to that end? Execute the common code and just make 2 short functions to return x and y?)
Functions by definition return a single value; that's the definition of a function. It should be able to be on the right hand side of an equal sign.
Subroutines, in SAS known as Call routines, are able to "return" zero, one, or more values. They do this by not returning anything directly (you cannot put a call routine on the right-hand side of an equal sign), but by modifying the arguments they are called with.
You see this in routines like call missing, which can set any number of values to missing; you see it a bit more directly in routines like call scan, which tells you the start position and length of the nth word in a string.
In order to do this, then, you would first want to change your function to a subroutine/call routine, i.e. replace function with subroutine, and then specify OUTARGS.
An example of this would be:
proc fcmp outlib=work.funcs.func;
subroutine roots(inval, outval_pos, outval_neg);
outargs outval_pos,outval_neg; *specifies these two will be "returned";
outval_pos = sqrt(inval);
outval_neg = -1*outval_pos;
endsub;
quit;
options cmplib=work.funcs;
data _null_;
x=9;
call missing(y_pos,y_neg);
call roots(x,y_pos, y_neg);
put x= y_pos= y_neg=;
run;

Composite trapezoid rule not running in Octave

I have the following code in Octave for implementing the composite trapezoid rule and for some reason the function only stalls whenever I execute it in Octave on f = #(x) x^2, a = 0, b = 4, TOL = 10^-6. Whenever I call trapezoid(f, a, b, TOL), nothing happens and I have to exit the Terminal in order to do anything else in Octave. Here is the code:
% INPUTS
%
% f : a function
% a : starting point
% b : endpoint
% TOL : tolerance
function root = trapezoid(f, a, b, TOL)
disp('test');
max_iterations = 10000;
disp(max_iterations);
count = 1;
disp(count);
initial = (b-a)*(f(b) + f(a))/2;
while count < max_iterations
disp(initial);
trap_0 = initial;
trap_1 = 0;
trap_1_midpoints = a:(0.5^count):b;
for i = 1:(length(trap_1_midpoints)-1)
trap_1 = trap_1 + (trap_1_midpoints(i+1) - trap_1_midpoints(i))*(f(trap_1_midpoints(i+1) + f(trap_1_midpoints(i))))/2;
endfor
if abs(trap_0 - trap_1) < TOL
root = trap_1;
return;
endif
intial = trap_1;
count = count + 1;
disp(count);
endwhile
disp(['Process ended after ' num2str(max_iterations), ' iterations.']);
I have tried your function in Matlab.
Your code is not stalling. It is rather that the size of trap_1_midpoints increases exponentionaly. With that the computation time of trap_1 increases also exponentionaly. This is what you experience as stalling.
I also found a possible bug in your code. I guess the line after the if clause should be initial = trap_1. Check the missing 'i'.
With that, your code still takes forever, but if you increase the tolerance (e.g. to a value of 1) your code return.
You could try to vectorize the for loop for speed up.
Edit: I think inside your for loop, a ) is missing after f(trap_1_midpoints(i+1).
After count=52 or so, the arithmetic sequence trap_1_midpoints is no longer representable in any meaningful fashion in floating point numbers. After count=1075 or similar, the step size is no longer representable as a positive floating point double number. That all is to say, the bound max_iterations = 10000 is ludicrous. As explained below, all computations after count=20 are meaningless.
The theoretical error for stepsize h is O(T·h^2). There is a numerical error accumulation in the summation of O(T/h) numbers that is of that size, i.e., O(mu/h) with mu=1ulp=2^(-52). Which in total means that the lowest error of the numerical integration can be expected around h=mu^(1/3), for double numbers thus h=1e-5 or in the algorithm count=17. This may vary with interval length and how smooth or wavy the function is.
One can expect the behavior that the error divides by four while halving the step size only for step sizes above this boundary 1e-5. This also means that abs(trap_0 - trap_1) is a reliable measure for the error of trap_0 (and abs(trap_0 - trap_1)/3 for trap_1) only inside this range of step sizes.
The error bound TOL=1e-6 should be met for about h=1e-3, which corresponds to count=10. If the recursion does not stop for count = 14 (which should give an error smaller than 1e-8) then the method is not accurately implemented.

Defining a Differential Equation in Octave

I am attempting to use Octave to solve for a differential equation using Euler's method.
The Euler method was given to me (and is correct), which works for the given Initial Value Problem,
y*y'' + (y')^2 + 1 = 0; y(1) = 1;
That initial value problem is defined in the following Octave function:
function [YDOT] = f(t, Y)
YDOT(1) = Y(2);
YDOT(2) = -(1 + Y(2)^2)/Y(1);
The question I have is about this function definition. Why is YDOT(1) != 1? What is Y(2)?
I have not found any documentation on the definition of a function using function [YDOT] instead of simply function YDOT, and I would appreciate any clarification on what the Octave code is doing.
First things first: You have a (non linear) differential equation of order two which will require you to have two initial conditions. Thus the given information from above is not enough.
The following is defined for further explanations: A==B means A is identical to B; A=>B means B follows from A.
It seems you are mixing a few things. The guy who gave you the files rewrote the equation in the following way:
y*y'' + (y')^2 + 1 = 0; y(1) = 1; | (I) y := y1 & (II) y' := y2
(I) & (II)=>(III): y' = y2 = y1' | y2==Y(2) & y1'==YDOT(1)
Ocatve is "matrix/vector oriented" so we are writing everything in vectors or matrices. Rather writing y1=alpha and y2=beta we are writing y=[alpha; beta] where y(1)==y1=alpha and y(2)==y2=beta. You will soon realize the tremendous advantage of using especially this mathematical formalization for ALL of your problems.
(III) & f(t,Y)=>(IV): y2' == YDOT(2) = y'' = (-1 -(y')^2) / y
Now recall what is y' and y from the definitions in (I) and (II)!
y' = y2 == Y(2) & y = y1 == Y(1)
So we can rewrite equation (IV)
(IV): y2' == YDOT(2) = (-1 -(y')^2) / y == -(1 + Y(2)^2)/Y(1)
So from equation (III) and (IV) we can derive what you already know:
YDOT(1) = Y(2)
YDOT(2) = -(1 + Y(2)^2)/Y(1)
These equations are passed to the solver. Differential equations of all types are solved numerically by retrieving the "next" value in a near neighborhood to some "previously known" value. (The step size inside this neighborhood is one of the key questions when writing solvers!) So your solver uses your initial condition Y(1)==y(1)=1 to make the next step and calculate the "next" value. So right at the start YDOT(1)=Y(2)==y(2) but you didn't tell us this value! But from then on YDOT(1) is varied by the solver in dependency to the function shape to solve your problem and give you ONE unique y(t) solution.
It seems you are using Octave for the first time so let's make a last comment on function [YDOT] = f(t, Y). In general a function is defined in this way:
function[retVal1, retVal2, ...] = myArbitraryName(arg1, arg2, ...)
Where retVal is the return value or output and arg is the argument or input.

Javascript - Arguments Vs Nested functions Vs Performance

Javascript noob question - which one of the following is best practice and performance friendly, also welcome any other suggestions too. This is simplest version of original project. There will be 20+ variables and 10+ inner functions (Ex: 'process' in the case).
The advantage of Method 1 is it doesn't need to send arguments to the functions but as it nests all the functions inside the main function (possibly regenerate all the inner function for each instance of Foo). While the method 2 is free from function nesting but requires lot of arguments. Note that also there will be multiple instance of Foo constructor.
Method 1:
function Foo () {
var a = 1;
var b = 2;
var c = (a+b)/2;
var $element = $('#myElement');
var process = function (){
var x = a+b+c;
$element.css('left', x)
return x;
}
x = process ();
}
Method 2:
function Foo () {
var a = 1;
var b = 2;
var c = (a+b)/2;
var $element = $('#myElement');
x = process (a, b, c, $element);
}
function process (a, b, c, $element){
$element.css('left', x)
return x;
}
The separated functions are definitely the way to go for performance. While there are situations where the variable scoping of nested functions would be nice to have, the performance hit can be huge if the function is large.
Keep in mind that every time Foo if called, var process is reallocating all the memory for the new function that is being created, rather than keeping the function in memory and just passing it new parameters. If the function is big, this is going to be a pretty intense task for the Javascript interpreter.
Here are some hard numbers that may help as well (Contains performance comparisons and actual benchmarks that you can run in your own browser): http://jsperf.com/nested-functions-speed, http://jsperf.com/nested-named-functions/5
Actually browsers do optimize even nested functions to where performance differences compared to functions declared in outer scope become negligible.
I blogged my findings and created a performance test to support this claim.
EDIT: The test was broken, after fixing the test shows that it's still faster not to nest functions.