Taylor 4th Order Code

I am having a problem with my code not generating the correct number. I think my problem lies in the way I am defining my functions. The answer I should be getting when n=1 is -987.75. But I have looked at the code several times, but I do not see what could be the problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Taylor-Series_4th-order.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <cmath>

using namespace std;

float Taylor4(float a, float xa, float b, int n);

#define dx1(t,x)				(1 + pow(b, 2) + pow(a, 3))   // (a,b) = (t,x)
#define dx2(t,x,dx1)			(2 * x*dx1 + 3 * pow(a, 2))
#define dx3(t,x,dx1,dx2)		(2 * x*dx2 + 2 * pow(dx1, 2) + 6 * a)
#define dx4(t,x,dx1,dx2,dx3)	(2 * x*dx3 + 6 * dx1*dx2 + 6)

void main()

{
	float ans;
	ans = Taylor4(1, -4, 2, 1);     //when n=1, ans should be -987.75 
	cout << "Answer is:" << ans;   //when n=100, ans should be 4.3712096
	cin.ignore();
}

float Taylor4(float a, float xa, float b, int n) // n is the number of intervals

{
	int k;
	float h, x, t, fx1, fx2, fx3, fx4, ti;

	t = a;
	x = xa;
	h = (b - a) / n;

	//	ti = t;

	cout << "k=0" << "\t a=" << t << "\t xa=" << x << "\t h=" << h << endl;

	for (k = 1; k < n + 1; k++)
	{
		fx1 = dx1(t, x);
		fx2 = dx2(t, x, fx1);
		fx3 = dx3(t, x, fx1, fx2);
		fx4 = dx4(t, x, fx1, fx2, fx3);

		x = x + h*(fx1 + 0.5*h*(fx2 + (1.0 / 3.0)*h*(fx3 + (float)0.25*h*fx4)));
		t = t + k*h;

		cout << "k=" << k << "\t a=" << t << "\t xa=" << x << "\t h=" << h << endl;
	}
	return (x);
}
Topic archived. No new replies allowed.