Differentiation using r - r

I'm new to using R or any type of programming and I'm trying to differentiate 3xcos(xy) with respect to x. I've tried four different ways and was wondering which one is best/correct.
D(expression(3*x*cos(xy)),"x")
D(expression(3*x*cos*(xy)),"x")
D(expression(3*x*cos*(xy)),"x")
D(expression(3*x*cos*(x*y)),"x")
thanks in advance
Shane

None of those.
This is the correct expression:
D(expression(3*x*cos(x*y)),"x")
#3 * cos(x * y) - 3 * x * (sin(x * y) * y)
This treats xy as one variable:
D(expression(3*x*cos(xy)),"x")
#3 * cos(xy)
This treats xy as one variable and cos as a variable (and not a function):
D(expression(3*x*cos*(xy)),"x")
#3 * cos * (xy)
This treats cos as a variable:
D(expression(3*x*cos*(x*y)),"x")
#3 * cos * (x * y) + 3 * x * cos * y

Related

R How to apply an equation to each row of 4 columns where each column is a parameter in the equation?

Below is a 3*4 matrix, where 2 columns represent the lat/lon coordinates of one location and the other two are coordinates of a second location. I'm trying to apply the great circle distance formula to each row. I'm pretty sure I should use something in the apply family, but can't figure out how.
d=as.data.frame(split(as.data.frame(c( 33.43527 ,-112.01194 , 37.72139 , -122.22111, -3.78444 , -73.30833 , -12.02667 , -77.12278,37.43555,38.88333,40.97667,28.81528)* pi/180),1:4))
colnames(d)=c('lat','lon','lat2','lon2')
This is the equation I would like to be applied to each of the 3 rows:
sum(acos(sin(lat) * sin(lat2) + cos(lat) * cos(lat2) * cos(lon2 -lon)) * 6371)*0.62137
The lat, lon, lat2, lon2 represent the column names in matrix d.
The final vector would look like this:
answer= 645.0978, 626.3632, 591.4725
Any help would be much appreciated.
You can use mapply and provide all 4 columns as parameter to the function as:
An option is to write as:
mapply(function(lat,lon,lat2,lon2)sum(acos(sin(lat) * sin(lat2) +
cos(lat) * cos(lat2) * cos(lon2 -lon)) * 6371)*0.62137,
d[,"lat"],d[,"lon"],d[,"lat2"],d[,"lon2"])
#Result: With updated data
#[1] 645.0978 626.3632 591.4725
We subset the columns of 'd' with [ (as it is a matrix - for data.frame, $ can also work), and then do the arithmetic
(acos(sin(d[,"lat"]) * sin(d[,"lat2"]) +
cos(d[,"lat"]) * cos(d[,"lat2"]) *
cos(d[,"lon2"] -d[,"lon"])) * r)*0.62137
#[1] 3153.471 10892.893 6324.854
This can also be done in a loop with apply
apply(d, 1, function(x) (acos(sin(x[1]) * sin(x[3]) +
cos(x[1]) * cos(x[3]) * cos(x[4] - x[2])) * r)* 0.62137)
#[1] 3153.471 10892.893 6324.854
The with function would allow you to use the expression:
(acos(sin(lat) * sin(lat2) + cos(lat) * cos(lat2) * cos(lon2 -lon)) * 6371)*0.62137
but you would need to transform it the d-matrix to a dataframe:
with(data.frame(d), ( acos( sin(lat) * sin(lat2) +
cos(lat) * cos(lat2) * cos(lon2 -lon) ) * 6371) *
0.62137
)
[1] 3153.471 10892.893 6324.854
The sum should not be used since the +, sin,cos, and acos functions are all vectorized but the sum function is not. I've tried to rearrange the indentation so the terms are easier to recognize.

Fast Quaternion-Vector Multiplication with other Transformation Matrices

I am currently trying to find an equivalent for the following equation:
vec_res = inverse(VM) * (q * (VM * vec_input) * conjugate(q))
where VM is a standard view matrix , q is a normalized quaternion, and vec_input a vector.
In the form:
vec_res = A * vec_input;
or
vec_res = q' * vec_input * conjugate(q');
From https://molecularmusings.wordpress.com/2013/05/24/a-faster-quaternion-vector-multiplication/ I am already calculating
vec_res = inverse(VM) * q * VM * vec_input * conjugate(q)
as
pN = (VM * vec_input);
vec3 tempVec = 2.0 * cross(q.xyz, pN);
pN = pN + q.w * tempVec + cross(q.xyz, tempVec);
pN = inverse(VM) * pN;
My question is, do I have the right to rewrite the equation like this ?
vec_res = (inverse(VM) * conversion_to_matrix(q) * VM) * vec_input
Where conversion_to_matrix is the rotation matrix calculated as explained in: http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/
If no, what is the math to be used behind ?
Note that multiplying your vector with
inverse(VM) * conversion_to_matrix(q) * VM
is not the same as multiplying it with
conversion_to_matrix(q)
since matrix multiplication is not commutative. So you really have to compute the entire matrix given in the first formula above.
vec_res = (inverse(VM) * conversion_to_matrix(q) * VM) * vec_input
Is perfectly valid.
The problem is...
inverse(VM) * conversion_to_matrix(q) * VM
is NOT equal to
conversion_to_matrix(q)
Therefore you have to keep the original equation in its entirety.

How to find where an equation equals zero

Say I have a function and I find the second derivative like so:
xyr <- D(expression(14252/(1+exp((-1/274.5315)*(x-893)))), 'x')
D2 <- D(xyr, 'x')
it gives me back as, typeof 'language':
-(14252 * (exp((-1/274.5315) * (x - 893)) * (-1/274.5315) * (-1/274.5315))/(1 +
exp((-1/274.5315) * (x - 893)))^2 - 14252 * (exp((-1/274.5315) *
(x - 893)) * (-1/274.5315)) * (2 * (exp((-1/274.5315) * (x -
893)) * (-1/274.5315) * (1 + exp((-1/274.5315) * (x - 893)))))/((1 +
exp((-1/274.5315) * (x - 893)))^2)^2)
how do I find where this is equal to 0?
A little bit clumsy to use a graph/solver for this, since your initial function as the form:
f(x) = c / ( 1 + exp(ax+b) )
You derive twice and solve for f''(x) = 0 :
f''(x) = c * a^2 * exp(ax+b) * (1+exp(ax+b)) * [-1 + exp(ax+b)] / ((1+exp(ax+b))^3)
Which is equivalent that the numerator equals 0 - since a, c, exp() and 1+exp() are always positive the only term which can be equal to zero is:
exp(ax+b) - 1 = 0
So:
x = -b/a
Here a =-1/274.5315, b=a*(-893). So x=893.
Just maths ;)
++:
from applied mathematician point of view, it's always better to have closed form/semi-closed form solution than using solver or optimization. You gain in speed and in accuracy.
from pur mathematician point of view, it's more elegant!
You can use uniroot after having created a function from your derivative expression:
f = function(x) eval(D2)
uniroot(f,c(0,1000)) # The second argument is the interval over which you want to search roots.
#Result:
#$root
#[1] 893
#$f.root
#[1] -2.203307e-13
#$iter
#[1] 7
#$init.it
#[1] NA
#$estim.prec
#[1] 6.103516e-05

how to get modulo of a value in exponential form

Question is about the modulo operator on very large numbers.
For example consider a question where the total number of permutations are to be calculated.
Consider a number of 90 digits with each of the 9 numbers (1 to 9) repeating 10 times
so 90!/(10!)^9) is to be calculated
After reading many answers on StackOverflow I used logarithms to do it.
Now consider the log value to be 1923.32877864.
Now my question is how can I display the answer (i.e. 10 ^ log10(value) ) modulo of "m"?
And is this the best method for calculating the possible number of permutations?
Edit
Got the solution :)
Thanks to duedl0r.
Did it the way you specified using Modular Multiplicative Inverse.Thanks :)
I'm not sure whether this is actually possible and correct, but let me summarize my comments and extend the answer from Miky Dinescu.
As Miky already wrote:
a × b ≣m am × bm
You can use this in your equality:
90! / 10!^9 ≣m x
Calculate each term:
90!m / 10!^9m ≣m x
Then find out your multiplicative inverse from 10!^9m. Then multiplicate the inverse with 90!m.
update
This seems to be correct (at least for this case :)). I checked with wolfram:
(90!/10!^9) mod (10^9+7) = 998551163
This leads to the same result:
90! mod (10^9+7) = 749079870
10!^9 mod (10^9+7) = 220052161
do the inverse:
(220052161 * x) mod(10^9+7) = 1 = 23963055
then:
(749079870*23963055) mod (10^9+7) = 998551163
No proof, but some evidence that it might work :)
I would argue that the way to compute the total number of permutations modulo m, where m is an arbitrary integer (usually chosen to be a large prime number) is to use the following property:
(a * b) % m = ((a % m) * (b % m)) % m
Considering that the total number of permutations of N is N! = 1 * 2 * 3 * .. * N, if you need to compute N! % m, you can essentially apply the property above for multiplication modulo m, and you have:
((((1 * (2 % m)) % m) * (3 % m)) % m) * ..
EDIT
In order to compute the 90! / (10! ^ 9) value you could simplify the factors and then use multiplication modulo m to compute the final result modulo m.
Here's what I'm thinking:
90! = 10! * (11 * 12 * .. * 20) * (21 * 22 * .. * 30) * .. * (81 * 82 * .. * 90)
You can then rewrite the original expression as:
(10! * (11 * 12 * .. * 20) * (21 * 22 * .. * 30) * .. * (81 * 82 * .. * 90)) / (10! * 10! * ... * 10!)
At the numerator, you have a product of 9 factors - considering each expression in parenthesis a factor. The same is true for the denominator (you have 9 factors, each equal to 10!).
The first factor at the denominator is trivial to simplify. After that you still have 8 pairs that need simplification.
So, you can factor each term of the products and simplify the denominator away. For example:
11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 <=> 11 * 2 * 2 * 3 * 13 * 2 * 7 * 3 * 5 * 2 * 2 * 2 * 2 * 17 * 2 * 9 * 2 * 2 * 5
The denominator will always be: 2 * 3 * 2 * 2 * 5 * 2 * 3 * 7 * 2 * 2 * 2 * 2 * 3 * 3 * 2 * 5
After the simplification the second pair reduces to : 2 * 2 * 11 * 13 * 17 * 19
The same can be applied to each subsequent pair and you will end up with a simple product that can be computed modulo m using the formula above.
Of course, efficiently implementing the algorithm to perform the simplification will be tricky so ultimately there has to be a better way that eludes me now.

Drawing a triangle in a coordinate plane given its three sides

The length of three sides of the triangle, a, b and c will be given, and I need to find the coordinates of the vertices. The center (probably the circumcenter) can either be the origin or (x,y).
Can anyone point me in the right direction?
I've read brainjam's answer and checked whether his answer is true and he is right.
Calculation:
O(0;0), A(a;0) and B(x;y) are the three points of the triangle. C1 is the circle around A and r1 = c; C2 is the circle around O and r2 = b. B(X;Y) is the intersection of C1 and C2, which means that the point is on both of the circles.
C1: (x - a) * (x - a) + y * y = c * c
C2: x * x + y * y = b * b
y * y = b * b - x * x
(x - a) * (x - a) + b * b - x * x = c * c
x * x - 2 * a * x + a * a + b * b - x * x - c * c = 0
2 * a * x = (a * a + b * b - c * c)
x = (a * a + b * b - c * c) / (2 * a)
y * y = b * b - ((a * a + b * b - c * c) / (2 * a)) * ((a * a + b * b - c * c) / (2 * a))
y = +- sqrt(b * b - ((a * a + b * b - c * c) / (2 * a)) * ((a * a + b * b - c * c) / (2 * a)))
Place the first vertex at the origin (0,0). Place the second vertex at (a,0). To compute the third vertex, find the intersection of the two circles with centers (0,0) and (a,0) and radii b and c.
Update: Lajos Arpad has given the details of computing the location of the third point in this answer. It boils down to (x,y) where x = (b2+a2-c2)/2a and y=±sqrt(b2-x2)
This question and the answers helped me out today in implementing this. It will calculate the unknown vertices, "c" of circle intersections given 2 known points (a, b) and the distances (ac_length, bc_length) to the 3rd unknown vertex, "c".
Here is my resulting python implementation for anyone interested.
I also referenced the following:
http://mathworld.wolfram.com/RadicalLine.html
http://mathworld.wolfram.com/Circle-CircleIntersection.html
Using django's geos module for the Point() object, which could be replaced with shapely, or point objects removed altogether really.
from math import sqrt
from django.contrib.gis.geos import Point
class CirclesSeparate(BaseException):
pass
class CircleContained(BaseException):
pass
def discover_location(point_a, point_b, ac_length, bc_length):
"""
Find point_c given:
point_a
point_b
ac_length
bc_length
point_d == point at which the right-angle to c is formed.
"""
ab_length = point_a.distance(point_b)
if ab_length > (ac_length + bc_length):
raise CirclesSeparate("Given points do not intersect!")
elif ab_length < abs(ac_length - bc_length):
raise CircleContained("The circle of the points do not intersect")
# get the length to the vertex of the right triangle formed,
# by the intersection formed by circles a and b
ad_length = (ab_length**2 + ac_length**2 - bc_length**2)/(2.0 * ab_length)
# get the height of the line at a right angle from a_length
h = sqrt(abs(ac_length**2 - ad_length**2))
# Calculate the mid point (point_d), needed to calculate point_c(1|2)
d_x = point_a.x + ad_length * (point_b.x - point_a.x)/ab_length
d_y = point_a.y + ad_length * (point_b.y - point_a.y)/ab_length
point_d = Point(d_x, d_y)
# get point_c location
# --> get x
c_x1 = point_d.x + h * (point_b.y - point_a.y)/ab_length
c_x2 = point_d.x - h * (point_b.y - point_a.y)/ab_length
# --> get y
c_y1 = point_d.y - h * (point_b.x - point_a.x)/ab_length
c_y2 = point_d.y + h * (point_b.x - point_a.x)/ab_length
point_c1 = Point(c_x1, c_y1)
point_c2 = Point(c_x2, c_y2)
return point_c1, point_c2
When drawing an unknown triangle, it's usually easiest to pick one side (say, the longest) and place it horizontally or vertically. The endpoints of that side make up two of the triangle's vertices, and you can calculate the third by subdividing the triangle into two right triangles (the other two sides are the hypotenuses) and using the inverse sine/cosine functions to figure out the missing angles. By subdividing into right triangles, I mean something that looks like the image here: http://en.wikipedia.org/wiki/File:Triangle.TrigArea.svg Your first side would be AC in that drawing.
Once you have the triangle figured out, it should be easy to calculate it's center and translate it so that it is centered on whatever arbitrary center point you like.
First check the that the triangle is possible:
a+b >= c
b+c >= a
c+a >= b
Then, if it is, solve for the intersection of the two circles. The basic vertices are
{0,0}, {a,0}, {x,y}
where
x = (a^2-b^2+c^2)/(2a)
y = sqrt(c^2-x^2)
Finding the circumcenter is pretty easy from this point.

Resources