Big numbers in function in windows forms - c#

im trying to do a function graph, its working but for some reason when i display function its giving me big numbers, i dunno why code looks fine to me, maybe i did something wrong with sample that i use. If you, for some reason, want to know what writen in these 3 textbox, here - first one is starting point, second one is end point, and last one is step.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
{
{
double xn = Convert.ToDouble(textBox1.Text);
double xk = Convert.ToDouble(textBox2.Text);
double xh = Convert.ToDouble(textBox3.Text);
if ((xn >= xk) || (xh > (xk - xn))) { MessageBox.Show("Данные заполнены неверно"); }
else
{
double z;
double x = xn;
while (x <= xk)
{
if (x <= 0) z = (1 + x) / Math.Pow(1 + Math.Pow(x, 2), 1 / 3);
else
if (x > 0 && x <= 1) z = -x + Math.Exp(-2 * x);
else z = Math.Pow(Math.Abs(2 - x), 1 / 3);
chart1.Series[0].Points.AddXY(x, z);
x += xh;
}
}
}
}
}

I believe your problem might be with the division between two integers of 1 / 3 in the expression
Math.Pow(1 + Math.Pow(x, 2), 1 / 3)
because
double oneThirdWrong = 1 / 3; // is equal to 0
and you may be expecting
double oneThirdRight = 1 / (double)3; // is 0.333...
Test Code (in .Net Core 3)
Console.WriteLine($"One-third wrong {1/3}" );
Console.WriteLine($"One-third right {1/3.0}" );

Related

Why does C# give an incorrect result in the console? [duplicate]

This question already has answers here:
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 2 years ago.
I need to complete a task - to implement a solution to a formula in C#, but the result in the console is not what I need. The result should be -11.84361, but the console outputs 15.1676628055975. What's wrong with the code? What to fix?
namespace Exercise10
{
class Program
{
static void Main()
{
Number number1 = new Number();
number1.Z();
Console.ReadKey();
}
}
class Number
{
double x, y, znamenatel, znamenatelh, virazhenie;
public void Z()
{
M:
Console.Write("Введите число x: ");
x = double.Parse(Console.ReadLine());
Console.Write("Введите число y: ");
y = double.Parse(Console.ReadLine());
znamenatelh = Math.Pow(Math.E, 2) - Math.Pow(x + y, 3 / 4);
if (znamenatelh < 0)
{
Console.WriteLine("Нельзя извлечь корень из отрицательного числа. Введите числа заново.");
goto M;
}
znamenatel = Math.Pow(znamenatelh, 1 / 3);
if (znamenatel == 0)
{
Console.WriteLine("Нельзя делить на нуль. Введите числа заново.");
goto M;
}
void Z_()
{
virazhenie = (x / znamenatel) + Math.Pow(Math.Pow(x - y, Math.Sin(x * y)) / znamenatel, 7 / 3);
Console.Write($"Z({x}, {y}) = {virazhenie}");
}
Z_();
}
}
} // <---- for some reason leaves the block
Here is all the information about the program and what should happen.
When you divide integer by integer the result is integer as well; in your case
3 / 4 == 0
1 / 3 == 0
7 / 3 == 2
In order to get floating point results (0.75, 0.33333, 2.33333) you should divide floating point values: 3.0 / 4.0, 1.0 / 3.0, 7.0 / 3.0:
// znamenatel' is Russian for "denominator"
znamenatelh = Math.Pow(Math.E, 2) - Math.Pow(x + y, 3.0 / 4.0);
...
// znamenatel' is Russian for "denominator"
znamenatel = Math.Pow(znamenatelh, 1.0 / 3.0);
...
// virazhenie is Russian for "formula" or "expression"
virazhenie = (x / znamenatel) + Math.Pow(Math.Pow(x - y, Math.Sin(x * y)) / znamenatel, 7.0 / 3.0);
Side note: goto M; is evil, turn
label M;
...
if (condition)
goto M;
construction into loop, e.g.
while (true) {
...
if (condition)
continue;
break;
}
Edit: Let's extract computation:
private static double Compute(double x, double y) {
if (x < y)
return double.NaN;
double denominator = Math.Exp(2) - Math.Pow(x + y, 3.0 / 4.0);
if (denominator == 0)
return x < 0 ? double.NegativeInfinity :
(x == 0) || (x == y) ? double.NaN :
double.PositiveInfinity;
denominator = Math.Pow(Math.Abs(denominator), 1.0 / 3.0) * Math.Sign(denominator);
double result = x / denominator;
double fraction = Math.Pow(x - y, Math.Sin(x * y)) / denominator;
result += Math.Pow(Math.Abs(fraction), 7.0 / 3.0) * Math.Sign(fraction);
return result;
}
UI (Simplified)
public void Z() {
double z = 0.0;
while (true) {
Console.WriteLine("Enter x: ");
double x = double.Parse(Console.ReadLine());
Console.WriteLine("Enter y: ");
double y = double.Parse(Console.ReadLine());
z = Compute(x, y);
if (!double.IsNaN(z) && !double.IsInfinity(z))
break;
Console.WriteLine("Invalid x and (or) y. Please, try again.");
}
Console.WriteLine(z);
}
Demo:
Console.Write(Compute(15, 5));
Outcome:
-11.8436193845787

What is the workflow of Pow(x,y) function?

I'm going through "sololearn" and udemy courses to try to learn C#. I am doing the challenges but could not figure out how the below code resulted with 32 (as in 32 is the correct answer here and I am trying to find out why). Can someone explain this process to me, the method calling itself is throwing me I think.
static double Pow(double x, int y)
{
if (y == 0)
{
return 1.0;
}
else
{
return x * Pow(x, y - 1);
}
}
static void Main()
{
Console.Write(Pow(2, 5));
}
Please excuse my bad coding. I am trying to do it on mobile, which is difficult, the answer was 32. Can someone explain why?
Edit: Aplogies here is how I work through it. Pass 2 and 5 to Pow, check if y == 0 which is false, it is now y == 5 so x * pow(x, y-1) formula will be active. X is still 2, y is now 4 which means it fails the check again on whether it equals 0, this loop continues until it returns the 1.0, x has remained at 2 so 2 * 1.0 = 2 and not 32?
First thing to note is that this is NOT how you would normally implement a power function. It's done this way to demonstrate recursion.
With that out the way, let's look at what happens when you call Pow(2, 5):
Pow(x = 2, y = 5)
-> return 2 * Pow(2, 4)
<- 2 * 16 = 32
Pow(x = 2, y = 4)
-> return 2 * Pow(2, 3)
<- 2 * 8 = 16
Pow(x = 2, y = 3)
-> return 2 * Pow(2, 2)
<- 2 * 4 = 8
Pow(x = 2, y = 2)
-> return 2 * Pow(2, 1)
<- 2 * 2 = 4
Pow(x = 2, y = 1)
-> return 2 * Pow(2, 0)
<- 2 * 1 = 2
Pow(x = 2, y = 0)
-> return 1 (because y == 0)
<- 1
To read this representation of the recursive call stack, work your way from the top to the bottom looking at how the arguments change; then work your way back up from the bottom to the top looking at the return values (which I indicate with <-).
Ok so let's go through the whole thing.
First of all, a static function is one that can be called without need to instantiate an object. There is one signature that all objects of the same class share. The double is a type within C# and its appearing here to show what the final output type of the function will be. Pow is the name of the function, double x, int y are parameters described by their type (not very well named but we'll leave that for another day)
So x is a number and y is the power of that number. There is a conditional here to check for two outcomes. If y is 0 then the answer is always 1, simple maths. Otherwise, the function performs the arithmetic using recursion (it calls itself again until it meets a terminating condition). The reason we get 32 is because 2x2x2x2x2 = 32. It is 2 to the power of 5.
I'm presuming you know what main and console.write are.
That method basically computes "x raised to the power of y". It does this in a recursive manner.
First, it defines a base case: anything raised to the power of 0 is 1.
Then, it defines what to do in all other cases: x * Pow(x, y - 1). Assuming y is big, what's x * Pow(x, y - 1)? It's x * x * Pow(x, y - 2), which in turn is x * x * x * Pow(x, y - 3). See the pattern here? Eventually, you will reach the point where the second argument, y - N, is 0, which as we have established, is 1. At that point, how many x * have we got? Exactly y.
Let's see this in action for Pow(2, 5):
Pow(2, 5)
2 * Pow(2, 4)
2 * 2 * Pow(2, 3)
2 * 2 * 2 * Pow(2, 2)
2 * 2 * 2 * 2 * Pow(2, 1)
2 * 2 * 2 * 2 * 2 * Pow(2, 0)
2 * 2 * 2 * 2 * 2 * 1
Hence the result 32.
Hello its recursion and it repeat until y=1, then return 2,then return 4, 8, 16, 32 at then end. 2^5=32
To be able to understand each action in this recursive behavior log all the details to see what is actually going on. Such as :
using System;
namespace Tester
{
class test
{
// What Pow actually does:
static double logPow(double x, int y) {
var old = x; // Hold the x
for (var i = 0; i < y; i++){ // do it y times
x = old * x; // Multiply with it's first self
}
return x;
}
static int counter = 0;
static double Pow(double x, int y) {
counter++;
Console.Write("Recursive action[" + counter + "] Y status ["+ y +"] : ");
if (y == 0)
{
Console.Write("return 1.0 = " + logPow(x, y) + " \n");
return 1.0;
}
else
{
Console.Write("return " + x + " * Pow(" + x + ", " + y + " - 1) = " + logPow(x,y-1) + " \n");
return x * Pow(x, y - 1);
}
}
static void Main() {
Console.Write("Last Result : " + Pow(2, 5));
}
}
}
Which gives the result :
Recursive action[1] Y status [5] : return 2 * Pow(2, 5 - 1) = 32
Recursive action[2] Y status [4] : return 2 * Pow(2, 4 - 1) = 16
Recursive action[3] Y status [3] : return 2 * Pow(2, 3 - 1) = 8
Recursive action[4] Y status [2] : return 2 * Pow(2, 2 - 1) = 4
Recursive action[5] Y status [1] : return 2 * Pow(2, 1 - 1) = 2
Recursive action[6] Y status [0] : return 1.0 = 2
Last Result : 32
You can debug your code by looking at these details.
Also you can have fun with it using this link : https://onlinegdb.com/Bysbxat9H

Cumulative Binomial Probability C#

I'm trying to calculate the cumulative binomial probability of 'n' trials, with 'p' probability and 'r' as the successful outcome of each trial. I have written the following code that works sometimes, but not always:
Console.WriteLine ();
Console.WriteLine ("B~(n, p)");
incorrectN:
Console.WriteLine ("Enter value of 'n': ");
int n = Convert.ToInt32 (Console.ReadLine ());
if (n < 0) {
Console.WriteLine ("ERROR: 'n' must be greater than 0");
goto incorrectN;
}
incorrectP:
Console.WriteLine ();
Console.WriteLine ("Enter value of 'p': ");
double p = Convert.ToDouble (Console.ReadLine ());
if (p > 1) {
Console.WriteLine ();
Console.WriteLine ("ERROR: 'p' must be between 0 and 1");
goto incorrectP;
}
Console.WriteLine ();
incorrectS:
int r = GetR();
int k = r;
double binomTotal = 0;
for (int j = r + 1; j > 0; j--) {
int nCr = Factorial(n) / (Factorial(n - (r - k)) * Factorial(r - k));
binomTotal = binomTotal + nCr * Math.Pow(p, (r - k)) * Math.Pow(1 - p, (n - (r - k)));
k--;
}
Console.WriteLine();
Console.WriteLine(binomTotal);
P.S. I have written the GetR() and Factorial() functions elsewhere within the class, where GetR() asks the user for the value of 'r' and Factorial() is defined as follows:
public static int Factorial(int x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
I tested the code with values n = 10, p = 0.5 and r = 5 and the output is 0.623046875, which is correct. However, when I use n = 13, p = 0.35 and r = 7, I get 0.297403640622647 instead of 0.9538.
Any help would be much appreciated.
In addition to your own answer:
public static double Factorial(double x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
accepts a double parameter, which means that x is not restricted to be an integer.
So you could call your Factorial method like this.
var fac1 = Factorial(1.4);
var fac2 = Factorial(2.7);
However, this does not make sense since the factorial is defined only* for , meaning that
is undefined.
So, instead of using double and allowing for invalid inputs, you should be using long instead, which has a greater range than int.
public static long Factorial(long x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
* there are some cases where factorials can be used with real values as well - e.g. by using the gamma function - but I don't think they're relevant to your use case and therefore you should not allow invalid parameters.
Change:
public static int Factorial(int x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
To:
public static double Factorial(double x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
Because Factorial(13) is too large for Int32.

B-Spline recursive definition in C#

I'm trying to implement the recursive definition for B-Splines in c# but I can't get it right. Here's what I've done:
public static Double RecursiveBSpline(int i, Double[] t, int order, Double x)
{
Double result = 0;
if (order == 0)
{
if (t[i] <= x && x < t[i + 1])
{
result = 1;
}
else
{
result = 0;
}
}
else
{
Double denom1, denom2, num1, num2;
denom1 = t[i + order + 1] - t[i + 1];
denom2 = t[i + order] - t[i];
if (denom1 == 0)
{
num1 = 0;
}
else
{
num1 = t[i + order + 1] - x / denom1;
}
if (denom2 == 0)
{
num2 = 0;
}
else
{
num2 = x - t[i] / denom2;
}
result = num1 * RecursiveBSpline(i + 1, t, order - 1, x)
+ num2 * RecursiveBSpline(i, t, order - 1, x);
}
return result;
}
And here is how I call the function:
Double[] vect = new Double[] { 0, 1, 2, 3 };
MessageBox.Show(BSpline.RecursiveBSpline(0,vect,2,0.5).ToString());
I should see 0,125 on the screen, instead I get 0,25. The two denominator variables are used to check if they equal 0 and if they do, the number should be set to 0 by definition. Can someone point out where I'm getting this wrong?
Bear in mind, that the mathematical and logical operators in C# have a precedence order. Your second solution works fine if you put the right terms in braces (explanation follows). This line:
num2 = x - t[i] / denom2;
should be changed to:
num2 = (x - t[i]) / denom2;
and so on. Then the result is as desired: 0.125
The division operator has a higher order precedence as the addition operator. To affect the execution order use braces (everything in braces will be evaluated at first):
var r1 = 2 + 2 / 2; // Step1: 2 / 2 = 1 Step2: 2 + 1 Output: 3
var r2 = (2 + 2) / 2; // Step1: (2 + 2) = 4 Step2: 4 / 2 = 2 Output: 2

Curve fitting points in 3D space

Trying to find functions that will assist us to draw a 3D line through a series of points.
For each point we know: Date&Time, Latitude, Longitude, Altitude, Speed and Heading.
Data might be recorded every 10 seconds and we would like to be able to guestimate the points in between and increase granularity to 1 second. Thus creating a virtual flight path in 3D space.
I have found a number of curve fitting algorithms that will approximate a line through a series of points but they do not guarantee that the points are intersected. They also do not take into account speed and heading to determine the most likely path taken by the object to reach the next point.
From a physics viewpoint:
You have to assume something about the acceleration in your intermediate points to get the interpolation.
If your physical system is relatively well-behaved (as a car or a plane), as opposed to for example a bouncing ball, you may go ahead supposing an acceleration varying linearly with time between your points.
The vector equation for a constant varying accelerated movement is:
x''[t] = a t + b
where all magnitudes except t are vectors.
For each segment you already know v(t=t0) x(t=t0) tfinal and x(tfinal) v(tfinal)
By solving the differential equation you get:
Eq 1:
x[t_] := (3 b t^2 Tf + a t^3 Tf - 3 b t Tf^2 - a t Tf^3 - 6 t X0 + 6 Tf X0 + 6 t Xf)/(6 Tf)
And imposing the initial and final contraints for position and velocity you get:
Eqs 2:
a -> (6 (Tf^2 V0 - 2 T0 Tf Vf + Tf^2 Vf - 2 T0 X0 + 2 Tf X0 +
2 T0 Xf - 2 Tf Xf))/(Tf^2 (3 T0^2 - 4 T0 Tf + Tf^2))
b -> (2 (-2 Tf^3 V0 + 3 T0^2 Tf Vf - Tf^3 Vf + 3 T0^2 X0 -
3 Tf^2 X0 - 3 T0^2 Xf + 3 Tf^2 Xf))/(Tf^2 (3 T0^2 - 4 T0 Tf + Tf^2))}}
So inserting the values for eqs 2 into eq 1 you get the temporal interpolation for your points, based on the initial and final position and velocities.
HTH!
Edit
A few examples with abrupt velocity change in two dimensions (in 3D is exactly the same). If the initial and final speeds are similar, you'll get "straighter" paths.
Suppose:
X0 = {0, 0}; Xf = {1, 1};
T0 = 0; Tf = 1;
If
V0 = {0, 1}; Vf = {-1, 3};
V0 = {0, 1}; Vf = {-1, 5};
V0 = {0, 1}; Vf = {1, 3};
Here is an animation where you may see the speed changing from V0 = {0, 1} to Vf = {1, 5}:
Here you may see an accelerating body in 3D with positions taken at equal intervals:
Edit
A full problem:
For convenience, I'll work in Cartesian coordinates. If you want to convert from lat/log/alt to Cartesian just do:
x = rho sin(theta) cos(phi)
y = rho sin(theta) sin(phi)
z = rho cos(theta)
Where phi is the longitude, theta is the latitude, and rho is your altitude plus the radius of the Earth.
So suppose we start our segment at:
t=0 with coordinates (0,0,0) and velocity (1,0,0)
and end at
t=10 with coordinates (10,10,10) and velocity (0,0,1)
I clearly made a change in the origin of coordinates to set the origin at my start point. That is just for getting nice round numbers ...
So we replace those numbers in the formulas for a and b and get:
a = {-(3/50), -(3/25), -(3/50)} b = {1/5, 3/5, 2/5}
With those we go to eq 1, and the position of the object is given by:
p[t] = {1/60 (60 t + 6 t^2 - (3 t^3)/5),
1/60 (18 t^2 - (6 t^3)/5),
1/60 (12 t^2 - (3 t^3)/5)}
And that is it. You get the position from 1 to 10 secs replacing t by its valus in the equation above.
The animation runs:
Edit 2
If you don't want to mess with the vertical acceleration (perhaps because your "speedometer" doesn't read it), you could just assign a constant speed to the z axis (there is a very minor error for considering it parallel to the Rho axis), equal to (Zfinal - Zinit)/(Tf-T0), and then solve the problem in the plane forgetting the altitude.
What you're asking is a general interpolation problem. My guess is your actual problem isn't due to the curve-fitting algorithm being used, but rather your application of it to all discrete values recorded by the system instead of the relevant set of values.
Let's decompose your problem. You're currently drawing a point in spherically-mapped 3D space, adjusting for linear and curved paths. If we discretize the operations performed by an object with six degrees of freedom (roll, pitch, and yaw), the only operations you're particularly interested in are linear paths and curved paths accounting for pitch and yaw in any direction. Accounting for acceleration and deceleration also possible given understanding of basic physics.
Dealing with the spherical mapping is easy. Simply unwrap your points relative to their position on a plane, adjusting for latitude, longitude, and altitude. This should allow you to flatten data that would otherwise exist along a curved path, though this may not strictly be necessary for the solutions to your problem (see below).
Linear interpolation is easy. Given an arbitrary number of points backwards in time that fit a line within n error as determined by your system,* construct the line and compute the distance in time between each point. From here, attempt to fit the time points to one of two cases: constant velocity or constant acceleration.
Curve interpolation is a little more difficult, but still plausible. For cases of pitch, yaw, or combined pitch+yaw, construct a plane containing an arbitrary number of points backwards in time, within m error for curved readouts from your system.* From these data, construct a planar curve and once again account for constant velocity or acceleration along the curve.
You can do better than this by attempting to predict the expected operations of a plane in flight as part of a decision tree or neural network relative to the flight path. I'll leave that as an exercise for the reader.
Best of luck designing your system.
--
* Both error readouts are expected to be from GPS data, given the description of the problem. Accounting and adjusting for errors in these data is a separate interesting problem.
What you need (instead of modeling the physics) is to fit a spline through the data. I used a numerical recipies book (http://www.nrbook.com/a has free C and FORTRAN algorithms. Look into F77 section 3.3 to get the math needed). If you want to be simple then just fit lines through the points, but that will not result in a smooth flight path at all. Time will be your x value, and each parameter loged will have it's own cublic spline parameters.
Since we like long postings for this question here is the full code:
//driver program
static void Main(string[] args)
{
double[][] flight_data = new double[][] {
new double[] { 0, 10, 20, 30 }, // time in seconds
new double[] { 14500, 14750, 15000, 15125 }, //altitude in ft
new double[] { 440, 425, 415, 410 }, // speed in knots
};
CubicSpline altitude = new CubicSpline(flight_data[0], flight_data[1]);
CubicSpline speed = new CubicSpline(flight_data[0], flight_data[2]);
double t = 22; //Find values at t
double h = altitude.GetY(t);
double v = speed.GetY(t);
double ascent = altitude.GetYp(t); // ascent rate in ft/s
}
// Cubic spline definition
using System.Linq;
/// <summary>
/// Cubic spline interpolation for tabular data
/// </summary>
/// <remarks>
/// Adapted from numerical recipies for FORTRAN 77
/// (ISBN 0-521-43064-X), page 110, section 3.3.
/// Function spline(x,y,yp1,ypn,y2) converted to
/// C# by jalexiou, 27 November 2007.
/// Spline integration added also Nov 2007.
/// </remarks>
public class CubicSpline
{
double[] xi;
double[] yi;
double[] yp;
double[] ypp;
double[] yppp;
double[] iy;
#region Constructors
public CubicSpline(double x_min, double x_max, double[] y)
: this(Sequence(x_min, x_max, y.Length), y)
{ }
public CubicSpline(double x_min, double x_max, double[] y, double yp1, double ypn)
: this(Sequence(x_min, x_max, y.Length), y, yp1, ypn)
{ }
public CubicSpline(double[] x, double[] y)
: this(x, y, double.NaN, double.NaN)
{ }
public CubicSpline(double[] x, double[] y, double yp1, double ypn)
{
if( x.Length == y.Length )
{
int N = x.Length;
xi = new double[N];
yi = new double[N];
x.CopyTo(xi, 0);
y.CopyTo(yi, 0);
if( N > 0 )
{
double p, qn, sig, un;
ypp = new double[N];
double[] u = new double[N];
if( double.IsNaN(yp1) )
{
ypp[0] = 0;
u[0] = 0;
}
else
{
ypp[0] = -0.5;
u[0] = (3 / (xi[1] - xi[0])) *
((yi[1] - yi[0]) / (x[1] - x[0]) - yp1);
}
for (int i = 1; i < N-1; i++)
{
double hp = x[i] - x[i - 1];
double hn = x[i + 1] - x[i];
sig = hp / hn;
p = sig * ypp[i - 1] + 2.0;
ypp[i] = (sig - 1.0) / p;
u[i] = (6 * ((y[i + 1] - y[i]) / hn) - (y[i] - y[i - 1]) / hp)
/ (hp + hn) - sig * u[i - 1] / p;
}
if( double.IsNaN(ypn) )
{
qn = 0;
un = 0;
}
else
{
qn = 0.5;
un = (3 / (x[N - 1] - x[N - 2])) *
(ypn - (y[N - 1] - y[N - 2]) / (x[N - 1] - x[N - 2]));
}
ypp[N - 1] = (un - qn * u[N - 2]) / (qn * ypp[N - 2] + 1.0);
for (int k = N-2; k > 0; k--)
{
ypp[k] = ypp[k] * ypp[k + 1] + u[k];
}
// Calculate 1st derivatives
yp = new double[N];
double h;
for( int i = 0; i < N - 1; i++ )
{
h = xi[i + 1] - xi[i];
yp[i] = (yi[i + 1] - yi[i]) / h
- h / 6 * (ypp[i + 1] + 2 * ypp[i]);
}
h = xi[N - 1] - xi[N - 2];
yp[N - 1] = (yi[N - 1] - yi[N - 2]) / h
+ h / 6 * (2 * ypp[N - 1] + ypp[N - 2]);
// Calculate 3rd derivatives as average of dYpp/dx
yppp = new double[N];
double[] jerk_ij = new double[N - 1];
for( int i = 0; i < N - 1; i++ )
{
h = xi[i + 1] - xi[i];
jerk_ij[i] = (ypp[i + 1] - ypp[i]) / h;
}
Yppp = new double[N];
yppp[0] = jerk_ij[0];
for( int i = 1; i < N - 1; i++ )
{
yppp[i] = 0.5 * (jerk_ij[i - 1] + jerk_ij[i]);
}
yppp[N - 1] = jerk_ij[N - 2];
// Calculate Integral over areas
iy = new double[N];
yi[0] = 0; //Integration constant
for( int i = 0; i < N - 1; i++ )
{
h = xi[i + 1] - xi[i];
iy[i + 1] = h * (yi[i + 1] + yi[i]) / 2
- h * h * h / 24 * (ypp[i + 1] + ypp[i]);
}
}
else
{
yp = new double[0];
ypp = new double[0];
yppp = new double[0];
iy = new double[0];
}
}
else
throw new IndexOutOfRangeException();
}
#endregion
#region Actions/Functions
public int IndexOf(double x)
{
//Use bisection to find index
int i1 = -1;
int i2 = Xi.Length;
int im;
double x1 = Xi[0];
double xn = Xi[Xi.Length - 1];
bool ascending = (xn >= x1);
while( i2 - i1 > 1 )
{
im = (i1 + i2) / 2;
double xm = Xi[im];
if( ascending & (x >= Xi[im]) ) { i1 = im; } else { i2 = im; }
}
if( (ascending && (x <= x1)) || (!ascending & (x >= x1)) )
{
return 0;
}
else if( (ascending && (x >= xn)) || (!ascending && (x <= xn)) )
{
return Xi.Length - 1;
}
else
{
return i1;
}
}
public double GetIntY(double x)
{
int i = IndexOf(x);
double x1 = xi[i];
double x2 = xi[i + 1];
double y1 = yi[i];
double y2 = yi[i + 1];
double y1pp = ypp[i];
double y2pp = ypp[i + 1];
double h = x2 - x1;
double h2 = h * h;
double a = (x-x1)/h;
double a2 = a*a;
return h / 6 * (3 * a * (2 - a) * y1
+ 3 * a2 * y2 - a2 * h2 * (a2 - 4 * a + 4) / 4 * y1pp
+ a2 * h2 * (a2 - 2) / 4 * y2pp);
}
public double GetY(double x)
{
int i = IndexOf(x);
double x1 = xi[i];
double x2 = xi[i + 1];
double y1 = yi[i];
double y2 = yi[i + 1];
double y1pp = ypp[i];
double y2pp = ypp[i + 1];
double h = x2 - x1;
double h2 = h * h;
double A = 1 - (x - x1) / (x2 - x1);
double B = 1 - A;
return A * y1 + B * y2 + h2 / 6 * (A * (A * A - 1) * y1pp
+ B * (B * B - 1) * y2pp);
}
public double GetYp(double x)
{
int i = IndexOf(x);
double x1 = xi[i];
double x2 = xi[i + 1];
double y1 = yi[i];
double y2 = yi[i + 1];
double y1pp = ypp[i];
double y2pp = ypp[i + 1];
double h = x2 - x1;
double A = 1 - (x - x1) / (x2 - x1);
double B = 1 - A;
return (y2 - y1) / h + h / 6 * (y2pp * (3 * B * B - 1)
- y1pp * (3 * A * A - 1));
}
public double GetYpp(double x)
{
int i = IndexOf(x);
double x1 = xi[i];
double x2 = xi[i + 1];
double y1pp = ypp[i];
double y2pp = ypp[i + 1];
double h = x2 - x1;
double A = 1 - (x - x1) / (x2 - x1);
double B = 1 - A;
return A * y1pp + B * y2pp;
}
public double GetYppp(double x)
{
int i = IndexOf(x);
double x1 = xi[i];
double x2 = xi[i + 1];
double y1pp = ypp[i];
double y2pp = ypp[i + 1];
double h = x2 - x1;
return (y2pp - y1pp) / h;
}
public double Integrate(double from_x, double to_x)
{
if( to_x < from_x ) { return -Integrate(to_x, from_x); }
int i = IndexOf(from_x);
int j = IndexOf(to_x);
double x1 = xi[i];
double xn = xi[j];
double z = GetIntY(to_x) - GetIntY(from_x); // go to nearest nodes (k) (j)
for( int k = i + 1; k <= j; k++ )
{
z += iy[k]; // fill-in areas in-between
}
return z;
}
#endregion
#region Properties
public bool IsEmpty { get { return xi.Length == 0; } }
public double[] Xi { get { return xi; } set { xi = value; } }
public double[] Yi { get { return yi; } set { yi = value; } }
public double[] Yp { get { return yp; } set { yp = value; } }
public double[] Ypp { get { return ypp; } set { ypp = value; } }
public double[] Yppp { get { return yppp; } set { yppp = value; } }
public double[] IntY { get { return yp; } set { iy = value; } }
public int Count { get { return xi.Length; } }
public double X_min { get { return xi.Min(); } }
public double X_max { get { return xi.Max(); } }
public double Y_min { get { return yi.Min(); } }
public double Y_max { get { return yi.Max(); } }
#endregion
#region Helpers
static double[] Sequence(double x_min, double x_max, int double_of_points)
{
double[] res = new double[double_of_points];
for (int i = 0; i < double_of_points; i++)
{
res[i] = x_min + (double)i / (double)(double_of_points - 1) * (x_max - x_min);
}
return res;
}
#endregion
}
You can find an approximation of a line that intersects points in 3d and 2d space using a Hough Transformation algorithm. I am only familiar with it's uses in 2d however but it will still work for 3d spaces given that you know what kind of line you are looking for. There is a basic implementation description linked. You can Google for pre-mades and here is a link to a 2d C implementation CImg.
The algorithm process (roughly)... First you find equation of a line that you think will best approximate the shape of the line (in 2d parabolic, logarithmic, exponential, etc). You take that formula and solve for one of the parameters.
y = ax + b
becomes
b = y - ax
Next, for each point you are attempting to match, you plugin the points to the y and x values. With 3 points, you would have 3 separate functions of b with respect to a.
(2, 3) : b = 3 - 2a
(4, 1) : b = 1 - 4a
(10, -5): b = -5 - 10a
Next, the theory is that you find all possible lines which pass through each of the points, which is infinitely many for each individual point however when combined in an accumulator space only a few possible parameters best fit. In practice this is done by choosing a range space for the parameters (I chose -2 <= a <= 1, 1 <= b <= 6) and begin plugging in values for the variant parameter(s) and solving for the other. You tally up the number of intersections from each function in an accumulator. The points with the highest values give you your parameters.
Accumulator after processing b = 3 - 2a
a: -2 -1 0 1
b: 1
2
3 1
4
5 1
6
Accumulator after processing b = 1 - 4a
a: -2 -1 0 1
b: 1 1
2
3 1
4
4
5 2
6
Accumulator after processing b = -5 - 10a
a: -2 -1 0 1
b: 1 1
2
3 1
4
5 3
6
The parameter set with the highest accumulated value is (b a) = (5 -1) and the function best fit to the points given is y = 5 - x.
Best of luck.
My guess is that a serious application of this would use a http://en.wikipedia.org/wiki/Kalman_filter. By the way, that probably wouldn't guarantee that the reported points were intersected either, unless you fiddled with the parameters a bit. It would expect some degree of error in each data point given to it, so where it thinks the object is at time T would not necessarily be where it was at time T. Of course, you could set the error distribution to say that you were absolutely sure you knew where it was at time T.
Short of using a Kalman filter, I would try and turn it into an optimisation problem. Work at the 1s granularity and write down equations like
x_t' = x_t + (Vx_t + Vx_t')/2 + e,
Vx_t_reported = Vx_t + f,
Vx_t' = Vx_t + g
where e, f, and g represent the noise. Then create a penalty function such as e^2 + f^2 + g^2 +...
or some weighted version such as 1.5e^2 + 3f^2 + 2.6g^2 +... according to your idea of what the errors really are and how smooth you wnat the answer to be, and find the values that make the penalty function as small as possible - with least squares if the equations turn out nicely.

Categories

Resources