Our teacher asked us to use C# to do a trapezoidal rule solution;
He wants us to break it down into three methods.
Below is the the question and my code so far:
Numerical integration is a technique that is particular suitable for
computer applications. In exercise we will try to implement the
trapezoidal rule. The integral of a mathematical function is the area
between the curve and the x-axis. If the area is divided into little
trapezoids, then the integral is approximated by the area of these
geometrical figures.
You will try to find the area under the curve y = 6x^2-7x+2 in the
region from x = 0.5 to x = 1.5 (N.B. your answer should work out to
about be 1.54, however the actual answer is 1.5). The area is given by
the formula
where y0 and y1 are the height of the vertical lines i.e. the value of
the function.
This problem can be decomposed into three parts as follows:
Write a method called EvaluateQuadraticValue(double x, double a, double b, double c) that takes four double arguments: the value of x,
the coefficient of the x2 term, the coefficient of the x and the
constant. The method will compute and return the result value of y
given by the expression y = ax2+ba+c.
Write a method called ComputeQuadraticValues(double startX, double increments, int numberOfIntervals, double a, double b, double c) that
takes six arguments: the start value of x, the increments and the
number of intervals and the coefficients of the quadratic equation.
This method will figure out the values of x0, x1, x2 etc. by invoking
the previous question. The results of the methods calls are collected
and returned as a double array.
Write a method called ApplyTrapeziodalRule(double startX, double endX, int numberOfIntervals, double a, double b, double c) . The
arguments are described in the previous question. This method calls
the previous method and process the double array that is returned to
compute the area under the curve by applying the formula
And my code so far:
public static double EvaluateQuadraticValue(double x, double a, double b, double c)
{
double y = a * Math.Pow(x, 2) + b * x + c;
Console.WriteLine("The y coordinate for this x is: {0}", y);
return y;
}
public static double[] ComputeQuadraticValues(double startX, double increments, int numberOfIntervals, double a, double b, double c)
{
double[] xPoints = new double[numberOfIntervals];
for (int index = 0; index < numberOfIntervals; index++)
{
xPoints[index] = startX;
Console.WriteLine("X{0} is {1}: ",index, xPoints[index]);
EvaluateQuadraticValue(startX, a, b, c);
startX = startX + increments;
}
return xPoints;
}
public static void ApplyTrapeziodalRule(double startX, double endX, int numberOfIntervals, double a, double b, double c)
{
double increments = Convert.ToInt32(Console.ReadLine());
double[] xPoints = ComputeQuadraticValues(startX, increments, numberOfIntervals, a, b, c);
//double[] values = a * Math.Pow(xPoints[i], 2) + b * xPoints[i] + c;
//double y = xPoints.Sum();
/*for (int i = 0; i < numberOfIntervals; i++)
{
}*/
//Console.WriteLine(y + " sum");
}
Currently I'm having trouble with the third method.
Since my double array from ComputeQuadraticValues() are x0, x1, x2 etc. How do I use this array to get (y0 + 2*y1 + 2*y2 + ...... + 2*yn + y(n+1))?
Any hints or tips are appreciated!
I agree with #MartinLiversage and also think there are some other tricky parts in the excersise. I'll try to do my best giving you a good answer. Let me know how this works for you.
This is the curve represented by 6x^2-7x+2 and you're required to compute the area in blue:
What you're doing is a numerical method, and the logic behind is that if you manage to split the area in an infinite number of points, you'll get the total area more accurately. The more points you add, more accurate the result will be.
The thing is that in Computer Sciences, infinity is not possible, because resources are limited and eventually you'll need to set a limit.
I've set 10 as number of interval (N) so you'll get 11 points and the sample is readable.
Now, your first method is just the helper in order to evaluate a function in the form ax^2 + bx + c.
public static double EvaluateQuadraticValue(double x, double a, double b, double c)
{
double y = a*Math.Pow(x,2) + b*x + c;
return y;
}
The second is where I think the problem is. I'd implement it like this:
public static double[] ComputeQuadraticValues(double startX, double increments, int numberOfIntervals, double a, double b, double c)
{
//We need numberOfInterval + 1 values
double[] yPoints = new double[numberOfIntervals+1];
for (int index = 0; index <= numberOfIntervals; index++, startX += increments)
{
//evaluate the function and get the y value for this x
yPoints[index] = EvaluateQuadraticValue(startX, a, b, c);
//Console.WriteLine("({0}, {1})", startX, yPoints[index]);
}
return yPoints;
}
And the last is the one who gets called by your Main() function:
public static void ApplyTrapezoidalRule(double startX, double endX, int numberOfIntervals, double a, double b, double c)
{
double increments = (endX - startX)/numberOfIntervals;
Console.WriteLine("increment: " + increments);
//compute the function value for each X (generated from startX + increment).
double[] yPoints = ComputeQuadraticValues(startX, increments, numberOfIntervals, a, b, c);
var first = (double)(endX - startX)/(2*numberOfIntervals);
Console.WriteLine("({0} - {1})/2*{2} = {3}", endX, startX, numberOfIntervals, first);
var sum = yPoints[0];
for (int i = 1; i <= numberOfIntervals; i++)
sum += 2 * yPoints[i];
sum += yPoints[numberOfIntervals];
var result = first * sum;
Console.WriteLine("result: " + result);
}
I've declared more variables so you'll see the process and the code is again more readable.
You can see this fiddle and play with the numberOfIntervals you pass in. Note that the value will be more accurate if you increase the number of intervals.
Hope this helps!
To me the description of ComputeQuadraticValues is confusing. It would make sense if it returned y0, y1, y2 etc. and not x0, x1, x2 etc. as stated.
Looking at your code for ComputeQuadraticValues you call EvaluateQuadraticValue (which computes y given x). However, the computed y value is not stored anywhere. You can rename xPoints to yPoints and then store the computed y value in that array before returning it as the result of the function.
With that change you should then be able to write a working version of ApplyTrapeziodalRule.
public double Integral(double[] x, double intPointOne, double intPointTwo)
{
double integral = 0;
double i = intPointOne;
do
{
integral += Function(x[i])*.001;
i = i + .001;
}
while (i <= intPointTwo);
return integral;
}
Here's a function I have to integrate a function from x1-x2 simply using a summation of parts. How can I make this loop more efficient (using less loops), but more accurate?
Where Function changes every iteration, but it should be irrelevant as it's order of magnitude (or boundary) should stay relatively the same...
1) look into section 4.3 of http://apps.nrbook.com/c/index.html for a different algorithm.
2) To control the accuracy/speed factor you may need to specify the bounds x_low and x_high as well as how many slices you want in the integral. So your function would look like this
// Integrate function f(x) using the trapezoidal rule between x=x_low..x_high
double Integrate(Func<double,double> f, double x_low, double x_high, int N_steps)
{
double h = (x_high-x_low)/N_steps;
double res = (f(x_low)+f(x_high))/2;
for(int i=1; i < N; i++)
{
res += f(x_low+i*h);
}
return h*res;
}
Once you understand this basic integration, you can move on to more elaborate schemes mentioned in Numerical Recipies and other sources.
To use this code issue a command like A = Integrate( Math.Sin, 0, Math.PI, 1440 );
Here the calculation of the integral through methods: left hand, trapezoidal and mid point
/// <summary>
/// Return the integral from a to b of function f
/// using the left hand rule
/// </summary>
public static double IntegrateLeftHand(double a,
double b,
Func<double,double> f,
int strips = -1) {
if (a >= b) return -1; // constraint: a must be greater than b
// if strips is not provided, calculate it
if (strips == -1) { strips = GetStrips(a, b, f); }
double h = (b - a) / strips;
double acc = 0.0;
for (int i = 0; i < strips; i++) { acc += h * f(a + i * h); }
return acc;
}
/// <summary>
/// Return the integral from a to b of function f
/// using the midpoint rule
/// </summary>
public static double IntegrateMidPoint(double a,
double b,
Func<double, double> f,
int strips = -1) {
if (a >= b) return -1; // constraint: a must be greater than b
// if strips is not provided, calculate it
if (strips == -1) { strips = GetStrips(a, b, f); }
double h = (b - a) / strips;
double x = a + h / 2;
double acc = 0.0;
while (x < b)
{
acc += h * f(x);
x += h;
}
return acc;
}
/// <summary>
/// Return the integral from a to b of function f
/// using trapezoidal rule
/// </summary>
public static double IntegrateTrapezoidal(double a,
double b,
Func<double, double> f,
int strips = -1) {
if (a >= b) return -1; // constraint: a must be greater than b
// if strips is not provided, calculate it
if (strips == -1) { strips = GetStrips(a, b, f); }
double h = (b - a) / strips;
double acc = (h / 2) * (f(a) + f(b));
for (int i = 1; i < strips; i++) { acc += h * f(a + i * h); }
return acc;
}
private static int GetStrips(double a,
double b,
Func<double, double> f) {
int strips = 100;
for (int i = (int)a; i < b; i++)
{
strips = (strips > f(i)) ? strips : (int)f(i);
}
return strips;
}
Console.WriteLine("w/ strips:{0}", IntegrateLeftHand(0, 3.14, Math.Sin, 1440));
Console.WriteLine("without strips:{0}", IntegrateMidPoint(0, 30, x => x * x));
// or with a defined method for f(x)
public static double myFunc(x) { return x * (x + 1); }
Console.WriteLine("w/ strips:{0}", IntegrateLeftHand(0, 20, myFunc, 200));
If you know functions in advance than you can analyze them and see what integration steps size works for your purposes. I.e. for linear function you need just one step, but for other functions you may need variable steps. At least see if you can get away with something like (pointTwo - pointOne)/1000.0.
If you need it for generic function and it is not homework you should strongly consider existing libraries or refreshing on your first-second year math courses...
Note your code actually have bug of not using i (which is very bad name for x):
for(x=intPointOne; x<=intPointTwo;x+=0.001)
{
integral += Function(x)*.001;
}
You are using the left-hand rule for integrating. This is only semi-accurate as long as the function has a positive and negative slope across the domain (since the errors of using the left end point cancel out).
I would recommend, at least, moving to the trapezoidal rule (calculate the area under the trapezoid formed by the set (x[i], 0), (x[i+0.001], 0), (x[i], Function(x[i]), (x[i+0.001], Function(x[x+0.001]).
An even better solution is to use Simpson's rule. It is a slower algorithm, but the accuracy should allow you to significantly increase your interval.
Look here: Numerical Integration for details.
I know this sounds like a homework assignment, but it isn't. Lately I've been interested in algorithms used to perform certain mathematical operations, such as sine, square root, etc. At the moment, I'm trying to write the Babylonian method of computing square roots in C#.
So far, I have this:
public static double SquareRoot(double x) {
if (x == 0) return 0;
double r = x / 2; // this is inefficient, but I can't find a better way
// to get a close estimate for the starting value of r
double last = 0;
int maxIters = 100;
for (int i = 0; i < maxIters; i++) {
r = (r + x / r) / 2;
if (r == last)
break;
last = r;
}
return r;
}
It works just fine and produces the exact same answer as the .NET Framework's Math.Sqrt() method every time. As you can probably guess, though, it's slower than the native method (by around 800 ticks). I know this particular method will never be faster than the native method, but I'm just wondering if there are any optimizations I can make.
The only optimization I saw immediately was the fact that the calculation would run 100 times, even after the answer had already been determined (at which point, r would always be the same value). So, I added a quick check to see if the newly calculated value is the same as the previously calculated value and break out of the loop. Unfortunately, it didn't make much of a difference in speed, but just seemed like the right thing to do.
And before you say "Why not just use Math.Sqrt() instead?"... I'm doing this as a learning exercise and do not intend to actually use this method in any production code.
First, instead of checking for equality (r == last), you should be checking for convergence, wherein r is close to last, where close is defined by an arbitrary epsilon:
eps = 1e-10 // pick any small number
if (Math.Abs(r-last) < eps) break;
As the wikipedia article you linked to mentions - you don't efficiently calculate square roots with Newton's method - instead, you use logarithms.
float InvSqrt (float x){
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759df - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;}
This is my favorite fast square root. Actually it's the inverse of the square root, but you can invert it after if you want....I can't say if it's faster if you want the square root and not the inverse square root, but it's freaken cool just the same.
http://www.beyond3d.com/content/articles/8/
What you are doing here is you execute Newton's method of finding a root. So you could just use some more efficient root-finding algorithm. You can start searching for it here.
Replacing the division by 2 with a bit shift is unlikely to make that big a difference; given that the division is by a constant I'd hope the compiler is smart enough to do that for you, but you may as well try it to see.
You're much more likely to get an improvement by exiting from the loop early, so either store new r in a variable and compare with old r, or store x/r in a variable and compare that against r before doing the addition and division.
Instead of breaking the loop and then returning r, you could just return r. May not provide any noticable increase in performance.
With your method, each iteration doubles the number of correct bits.
Using a table to obtain the initial 4 bits (for example), you will have 8 bits after the 1st iteration, then 16 bits after the second, and all the bits you need after the fourth iteration (since a double stores 52+1 bits of mantissa).
For a table lookup, you can extract the mantissa in [0.5,1[ and exponent from the input (using a function like frexp), then normalize the mantissa in [64,256[ using multiplication by a suitable power of 2.
mantissa *= 2^K
exponent -= K
After this, your input number is still mantissa*2^exponent. K must be 7 or 8, to obtain an even exponent. You can obtain the initial value for the iterations from a table containing all the square roots of the integral part of mantissa. Perform 4 iterations to get the square root r of mantissa. The result is r*2^(exponent/2), constructed using a function like ldexp.
EDIT. I put some C++ code below to illustrate this. The OP's function sr1 with improved test takes 2.78s to compute 2^24 square roots; my function sr2 takes 1.42s, and the hardware sqrt takes 0.12s.
#include <math.h>
#include <stdio.h>
double sr1(double x)
{
double last = 0;
double r = x * 0.5;
int maxIters = 100;
for (int i = 0; i < maxIters; i++) {
r = (r + x / r) / 2;
if ( fabs(r - last) < 1.0e-10 )
break;
last = r;
}
return r;
}
double sr2(double x)
{
// Square roots of values in 0..256 (rounded to nearest integer)
static const int ROOTS256[] = {
0,1,1,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9,9,9,
9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,
12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16 };
// Normalize input
int exponent;
double mantissa = frexp(x,&exponent); // MANTISSA in [0.5,1[ unless X is 0
if (mantissa == 0) return 0; // X is 0
if (exponent & 1) { mantissa *= 128; exponent -= 7; } // odd exponent
else { mantissa *= 256; exponent -= 8; } // even exponent
// Here MANTISSA is in [64,256[
// Initial value on 4 bits
double root = ROOTS256[(int)floor(mantissa)];
// Iterate
for (int it=0;it<4;it++)
{
root = 0.5 * (root + mantissa / root);
}
// Restore exponent in result
return ldexp(root,exponent>>1);
}
int main()
{
// Used to generate the table
// for (int i=0;i<=256;i++) printf(",%.0f",sqrt(i));
double s = 0;
int mx = 1<<24;
// for (int i=0;i<mx;i++) s += sqrt(i); // 0.120s
// for (int i=0;i<mx;i++) s += sr1(i); // 2.780s
for (int i=0;i<mx;i++) s += sr2(i); // 1.420s
}
Define a tolerance and return early when subsequent iterations fall within that tolerance.
Since you said the code below was not fast enough, try this:
static double guess(double n)
{
return Math.Pow(10, Math.Log10(n) / 2);
}
It should be very accurate and hopefully fast.
Here is code for the initial estimate described here. It appears to be pretty good. Use this code, and then you should also iterate until the values converge within an epsilon of difference.
public static double digits(double x)
{
double n = Math.Floor(x);
double d;
if (d >= 1.0)
{
for (d = 1; n >= 1.0; ++d)
{
n = n / 10;
}
}
else
{
for (d = 1; n < 1.0; ++d)
{
n = n * 10;
}
}
return d;
}
public static double guess(double x)
{
double output;
double d = Program.digits(x);
if (d % 2 == 0)
{
output = 6*Math.Pow(10, (d - 2) / 2);
}
else
{
output = 2*Math.Pow(10, (d - 1) / 2);
}
return output;
}
I have been looking at this as well for learning purposes. You may be interested in two modifications I tried.
The first was to use a first order taylor series approximation in x0:
Func<double, double> fNewton = (b) =>
{
// Use first order taylor expansion for initial guess
// http://www27.wolframalpha.com/input/?i=series+expansion+x^.5
double x0 = 1 + (b - 1) / 2;
double xn = x0;
do
{
x0 = xn;
xn = (x0 + b / x0) / 2;
} while (Math.Abs(xn - x0) > Double.Epsilon);
return xn;
};
The second was to try a third order (more expensive), iterate
Func<double, double> fNewtonThird = (b) =>
{
double x0 = b/2;
double xn = x0;
do
{
x0 = xn;
xn = (x0*(x0*x0+3*b))/(3*x0*x0+b);
} while (Math.Abs(xn - x0) > Double.Epsilon);
return xn;
};
I created a helper method to time the functions
public static class Helper
{
public static long Time(
this Func<double, double> f,
double testValue)
{
int imax = 120000;
double avg = 0.0;
Stopwatch st = new Stopwatch();
for (int i = 0; i < imax; i++)
{
// note the timing is strictly on the function
st.Start();
var t = f(testValue);
st.Stop();
avg = (avg * i + t) / (i + 1);
}
Console.WriteLine("Average Val: {0}",avg);
return st.ElapsedTicks/imax;
}
}
The original method was faster, but again, might be interesting :)
Replacing "/ 2" by "* 0.5" makes this ~1.5 times faster on my machine, but of course not nearly as fast as the native implementation.
Well, the native Sqrt() function probably isn't implemented in C#, it'll most likely be done in a low-level language, and it'll certainly be using a more efficient algorithm. So trying to match its speed is probably futile.
However, in regard to just trying to optimize your function for the heckuvit, the Wikipedia page you linked recommends the "starting guess" to be 2^floor(D/2), where D represents the number of binary digits in the number. You could give that an attempt, I don't see much else that could be optimized significantly in your code.
You can try
r = x >> 1;
instead of / 2 (also in the other place you device by 2).
It might give you a slight edge.
I would also move the 100 into the loop. Probably nothing, but we are talking about ticks in here.
just checking it now.
EDIT:
Fixed the > into >>, but it doesn't work for doubles, so nevermind.
the inlining of the 100 gave me no speed increase.