Logic for formula calculation - c

I need to compute the following problem in code:
x0 = 2 and xi = (−1/2) * x(sub i - 1) * sqrt(x(sub i - 1))
find the result of (1/e^(x1 + x2 + x3 + ...)).
(Or as marked up text)
Write a function of an appropriate type that calculates and returns the result of:
e(x1-1 - x2-1 + x3-1 - x4-1 + ...), for n elements, defined as: x0 = 2 and xi = -½√|xi-1|
It has to be done in C but I am just trying to figure out the logistics of it.
What I have thought till now : x0 has to be a variable initialized with 2 along with x1. x2, x3... will be calculated in a recursive function n-1 times. I am not sure how the results should be stored, also a variable or maybe an array? Would an array be appropriate??
Thank you.

Would it not be simpler to do it iteratively like this? I'm not actually sure if this generates the correct answer but this seems to be what your formula would imply.
long double
compute(unsigned n)
{
long double x = 2.0L;
for (unsigned i = 0; i < n; ++i)
x = (-(1.0L/2.0L) * x) * sqrtl(fabsl(x));
return x;
}

Related

Matrix where columns store the same information as rows - Efficient way to store [duplicate]

Which is the best way to store a symmetric matrix in memory?
It would be good to save half of the space without compromising speed and complexity of the structure too much. This is a language-agnostic question but if you need to make some assumptions just assume it's a good old plain programming language like C or C++..
It seems a thing that has a sense just if there is a way to keep things simple or just when the matrix itself is really big, am I right?
Just for the sake of formality I mean that this assertion is always true for the data I want to store
matrix[x][y] == matrix[y][x]
Here is a good method to store a symmetric matrix, it requires only N(N+1)/2 memory:
int fromMatrixToVector(int i, int j, int N)
{
if (i <= j)
return i * N - (i - 1) * i / 2 + j - i;
else
return j * N - (j - 1) * j / 2 + i - j;
}
For some triangular matrix
0 1 2 3
4 5 6
7 8
9
1D representation (stored in std::vector, for example) looks like as follows:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
And call fromMatrixToVector(1, 2, 4) returns 5, so the matrix data is vector[5] -> 5.
For more information see http://www.codeguru.com/cpp/cpp/algorithms/general/article.php/c11211/TIP-Half-Size-Triangular-Matrix.htm
I find that many high performance packages just store the whole matrix, but then only read the upper triangle or lower triangle. They might then use the additional space for storing temporary data during the computation.
However if storage is really an issue then just store the n(n+1)/2 elements making the upper triangle in a one-dimensional array. If that makes access complicated for you, just define a set of helper functions.
In C to access a matrix matA you could define a macro:
#define A(i,j, dim) ((i <= j)?matA[i*dim + j]:matA[j*dim + i])
then you can access your array nearly normally.
Well I would try a triangular matrix, like this:
int[][] sym = new int[rows][];
for( int i = 0; i < cols; ++i ) {
sym=new int[i+1];
}
But then you wil have to face the problem when someone wants to access the "other side". Eg he wants to access [0][10] but in your case this val is stored in[10][0] (assuming 10x10).
The probably "best" way is the lazy one - dont do anything until the user requests. So you could load the specific row if the user types somethin like print(matrix[4]).
If you want to use a one dimensional array the code would look something like this:
int[] new matrix[(rows * (rows + 1 )) >> 1];
int z;
matrix[ ( ( z = ( x < y ? y : x ) ) * ( z + 1 ) >> 1 ) + ( y < x ? y : x ) ] = yourValue;
You can get rid of the multiplications if you create an additional look-up table:
int[] new matrix[(rows * (rows + 1 )) >> 1];
int[] lookup[rows];
for ( int i= 0; i < rows; i++)
{
lookup[i] = (i * (i+1)) >> 1;
}
matrix[ lookup[ x < y ? y : x ] + ( x < y ? x : y ) ] = yourValue;
If you're using something that supports operator overloading (e.g. C++), it's pretty easy to handle this transparently. Just create a matrix class that checks the two subscripts, and if the second is greater than the first, swap them:
template <class T>
class sym_matrix {
std::vector<std::vector<T> > data;
public:
T operator()(int x, int y) {
if (y>x)
return data[y][x];
else
return data[x][y];
}
};
For the moment I've skipped over everything else, and just covered the subscripting. In reality, to handle use as both an lvalue and an rvalue correctly, you'll typically want to return a proxy instead of a T directly. You'll want a ctor that creates data as a triangle (i.e., for an NxN matrix, the first row will have N elements, the second N-1, and so on -- or, equivalantly 1, 2, ...N). You might also consider creating data as a single vector -- you have to compute the correct offset into it, but that's not terribly difficult, and it will use a bit less memory, run a bit faster, etc. I'd use the simple code for the first version, and optimize later if necessary.
You could use a staggered array (or whatever they're called) if your language supports it, and when x < y, switch the position of x and y. So...
Pseudocode (somewhat Python style, but not really) for an n x n matrix:
matrix[n][]
for i from 0 to n-1:
matrix[i] = some_value_type[i + 1]
[next, assign values to the elements of the half-matrix]
And then when referring to values....
if x < y:
return matrix[y][x]
else:
return matrix[x][y]

Generate MxN Matrix with MatLab Anonymous Function

Imagine for instance we have the following functions:
f = #(n) sin((0:1e-3:1) .* n * pi);
g = #(n, t) cos(n .^ 2 * pi ^2 / 2 .* t);
h = #(n) f(n) * g(n, 0);
Now, I would like to be able to enter an array of values for n into h and return a sum of the results for each value of n.
I am trying to be efficient, so I am avoiding the novice for-loop method of just filling out a pre-allocated matrix and summing down the columns. I also tried using arrayfun and converting the cell to a matrix then summing that, but it ended up being a slower process than the for-loop.
Does anyone know how I might do this?
The fact is the "novice" for-loop is going to be competitively as fast as any other vectorized solution thanks to improvements in JIT compilation in recent versions of MATLAB.
% array of values of n
len = 500;
n = rand(len,1);
% preallocate matrix
X = zeros(len,1001);
% fill rows
for i=1:len
X(i,:) = h(n(i)); % call function handle
end
out = sum(X,1);
The above is as fast as (maybe even faster):
XX = cell2mat(arrayfun(h, n, 'UniformOutput',false));
out = sum(XX,1);
EDIT:
Here it is computed directly without function handles in a single vectorized call:
n = rand(len,1);
t = 0; % or any other value
out = sum(bsxfun(#times, ...
sin(bsxfun(#times, n, (0:1e-3:1)*pi)), ...
cos(n.^2 * t * pi^2/2)), 1);

C program to calculate mathematical correlation function/autocorrelation function

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main ()
{
double g_1, e_1, e_2, e_3, e_4, e_5;
int k;
// double e[k];
e_1 = 3.0;
e_2 = 9.0;
e_3 = 27.0;
e_4 = 81.0;
e_5 = 243.0;
g_1 = ((e_1*e_2 + e_2*e_3 + e_3*e_4 + e_4*e_5)/5) - (((e_1)* + (e_2) + (e_3) +(e_4) + (e_5)/5)*((e_1)* + (e_2) + (e_3) +(e_4) + (e_5)/5));
printf("\n\n this is g(1): %f",g_1);
return (0);
}
I am trying to write a program that calculates the correlation between values. The mathematical function I have is the autocorrelation function or mathematical correlation function which is
g(T) = sum(from t = 1 to m-T) [ (e_t)*(e_(T+t)] - (sum(from t = 1 to m) [e_t/m] )^2
where m is the number of values I have.
Above I have tried to do the simplest version by taking 5 numbers and just plugging them into the formula. But eventually I need to be able to read a file containing any number of values from 100 to 5000 and find the correlation between them. I will worry about reading the file to the entries of an array later but first I would like to know is there a logical way of doing this using arrays?
For example I tried to do the following:
e[1] = 3.0;
e[2] = 9.0;
e[3] = 27.0;
e[4] = 81.0;
e[5] = 243.0;
for(k=1;k<=5;k++)
{
g[k]= ((e[k]*e[k+1] + e[k+1]*e[k+2] + e[k+2]*e[k+3] + e[k+3]*e[k+4])/5) - (((e[k] + e[k+1] + e[k+2] + e[k+3] + e[k+4])/5)*((e[k] + e[k+1] + e[k+2] + e[k+3] + e[k+4])/5))
}
But this would only make sense for k=1, because by the time it gets to k = 5, then k+1 will be 6, k+2 will be 7.. and I don't have these values.. But I'm not sure how exactly to program this.. Can anybody help?
Thank you
This is the formula using MathJax
g(\tau) = \sum_{\tau_{0}=1}^{m-\tau} ((\epsilon_{\tau{_0}} * \epsilon_{\tau+\tau_{0}})/m) - (\sum_{\tau_{0}=1}^m \epsilon_{\tau_{0}}/m)^2
an alternative form of the formula is:
g(\tau) = <\epsilon_{\tau_{0}}\epsilon_{\tau_{0}+\tau}>-<\epsilon_{\tau_{0}}>^2
where means expectation of a.
This is more of a how to read a math expression problem. It seems like in your example, m = 5, so the sums never reference beyond that.
I'm not entirely clear on your equation. Have tried Mathjax, but the formula is still not clear to me, but...
When translating a math expression to code, think of the summation sign (sigma) as equivalent to a for loop!
when writing the code, write (initially) in the most explicit way possible. For this problem code TWO for loops, one after the other, NOT nested. Each for loop does part of the calculation for g(k).
Get this to work for g(1). Then code a third for loop that wraps or surrounds the two loops you just got working. This loop will calculate g(1), g(2), etc. Note. if m is 5 and you only have 5 data points then you can only compute g(1), if m is 6 you can compute g(1) and g(2), etc.
Hope this helps, please post if you more information or questions.
To answer your comment, the following for loop implements a sum or sigma. Note. This is NOT exactly what your code should do, but it does demo using two for loops.
int g1; x = 0; y = 0;
int i;
// compute x = sum(g(i)) + sum(f(i))
// sum i = 0 to 2 [g(i)]
for (i=0; i < 3; i++) {x += g[i];}
// sum i = 0 to 1 [f(i)];
for (i=0; i < 2; i++) {y += f[i];}
g1 = x - y^2;
The C code you are looking for would be in this form:
int tau = 7
int m = 80;
double *e; /* An array filled with m values */
double lhs,rhs,answer;
int tau0;
/* Left Summation */
for(sum=0,tau0=1; tau0 < m-tau; ++tau0)
sum += e[tau0] * e[tau+tau0];
lhs = sum / m;
/* Right Summation */
for(sum=0,tau0=1; tau0 < m; ++tau0)
sum += e[tau0] / m;
rhs = sum * sum;
answer = lhs - rhs;
Hopefully this get you closer to your solution.

How would one write down this mathematical expression programmatically?

The sum of f(i) for all integers i =
k, k + 1, .., continuing only as long
as the condition p(i) holds.
I'm going for:
for (i = 0; i <= V_COUNT; i++) {
sum += sine_coeff[i] * pow(E, e_factor[i]) * sin(
(solar_coeff[i] * solar_anomaly)
+ (lunar_coeff[i] * lunar_anomaly)
+ (moon_coeff[i] * moon_argument)
);
}
based on the following Common LISP code:
(sigma ((v sine-coeff)
(w E-factor)
(x solar-coeff)
(y lunar-coeff)
(z moon-coeff))
(* v (expt cap-E w)
(sin-degrees
(+ (* x solar-anomaly)
(* y lunar-anomaly)
(* z moon-argument)))))))
where sigma is:
(defmacro sigma (list body)
;; TYPE (list-of-pairs (list-of-reals->real))
;; TYPE -> real
;; $list$ is of the form ((i1 l1)..(in ln)).
;; Sum of $body$ for indices i1..in
;; running simultaneously thru lists l1..ln.
`(apply '+ (mapcar (function (lambda
,(mapcar 'car list)
,body))
,#(mapcar 'cadr list))))
(for full source code, see Calendrical calculations source code
Edit
Thanks for all your answers. Investigating the code examples, I have come to the conclusion that, in programming terms, the author indeed ment that one has to loop over a certain set of values. From that, it was easy to conclude that p had to return False when it has run out of values, i.e. control has reached the end of the list.
Define a function p(), e.g.:
bool_t p(int i)
{
// some conditional code here, that returns TRUE or FALSE
}
It seems like you need to loop for an arbitrarily long time (i.e. there's no hard upper limit), and you need to stop looping when p(i) returns FALSE. Therefore, you probably want a loop something like this:
int sum = 0;
for (int i = k; p(i); i++)
{
sum += f(i);
}
Depending on how large i and sum can get, you may want to declare them as long rather than int.
Something like:
sum = 0;
i = k;
while (p(i))
sum += f(i++);

Find LineSegment that contains a Point

I have a Path and when user click on a segment I have to split it into two segments.
I have the point where user click but I can't find a method to get the LineSegment that contains that point.
I don't have to find the Path element... but the LineSegment of a collection of Segment that create the PathGeometry of the Path clicked.
How can i do?
I have some code that does this. Each of my points are stored in a Points collection rather than being stored as LineSegments, but it should work for you I think. The thickness parameter is the thickness of the line.
public int HitTestSegments(Point point, double thickness)
{
for (int i = 0; i < Points.Count; ++i)
{
Point p0 = Points[i];
Point p1 = (i + 1 < Points.Count) ? Points[i + 1] : Points[0];
Vector v = p1 - p0;
Vector w = point - p0;
double c1 = w * v;
double c2 = v * v;
double b = c1 / c2;
Point pb = p0 + b * v;
double distance = (point - pb).Length;
if (distance < thickness)
{
return i;
}
}
return -1;
}
I hacked this together from various samples on the internet, and my maths isn't amazing. It may not be the best code - if not, please suggest improvements.
But you have Point property, so basically you've got a Collecion of n+1 Points. Line between points is a simple linien equation. You have to check if your mouse's point solve this equation (interates through the collection for all lines).
The equation: 0 = Ax + By + C or simply y = ax + b
There are many ways to get the parameters of it.
From geometry we know, that (y1 - y2) * x + (x2 - x1) * y + (x1*y2 - x2*y1) = 0, where x1, y1 is the firs point of your line segment and x2, y2 is the second one. This is the formula of the line. To determine, if a given point P(X, Y) belongs to the line, you have to substitute it's coordinates to your line formula's left side and the result on the right side should be 0, or 0 +- \epsilon.
But you have not a line, you have it's segment, so you will have to add more checks, for instance, Px should not be less than x1, and no more than x2, etc.
To expand on what Shaman & lukas have said - what you really want to do is find the line segment that is nearest to to click point (As the user could not be expected to click exactly on the line)
To do this,go through each of the line segments and apply the `(y1 - y2) * x + (x2 - x1) * y + (x1*y2 - x2*y1)' formula to it and remove the sign of the answer - the line segmet that produces the smallest result is the one that is nearest to the click point.
If you have a lot of segments in your path, this might take a long time to execute, so there are probably some optimisations to be done - but that, as they say, is a whole new story.

Resources