# Truncated Sin Series in FORTRAN

1. Sep 15, 2011

### mattmac.nuke

I am very much confused and frustrated at this point and would just like to understand what I'm doing wrong... This program is supposed to calculate a truncated value of sine using it's series expansion beginning at i = 1. At values under 20 degrees it compares almost exactly with the intrinsic sine function, but after that it's as much as .06-.23 off! This is my first course in programming in general, and I've been very good at Fortran thus far, but there's something I'm missing in this case... This is the program I have been trying to fix:

program series
implicit none
real :: n_factorial, sin_x, x, v1, sum_1, n_1
integer :: n, i

write (*,*) 'enter n'
write (*,*) 'enter x in degrees'

n_factorial = 1
sin_x = 0
x = ((x*3.1415926535898)/180)
v1 = sin(x)

DO i = 1, n

n_1 = (2*i) - 1

n_factorial = n_factorial * n_1

sum_1 = (((-1)**(i-1)) * ((x**((2*i) - 1))/(n_factorial)))

sin_x = sin_x + sum_1

END DO

write (*,*) sin_x
write (*,*) ' '
write (*,*) v1
end program series

This is my first time posting on this site, and posting in general, I would infinitely appreciate the help in figuring out what's wrong!

2. Sep 15, 2011

### rcgldr

You didn't mention how truncated the series is. What value are you inputting for n? If the series is significantly truncated, then the error will get larger as the angle gets larger.

3. Sep 15, 2011

### uart

Hi Matt, the problem is with your factorial calculation. You're only multiplying the odd numbers so you're not getting the full factorial.

You could fix it by modifying the line "n_factorial = n_factorial * n_1" to something like,
n_factorial = n_factorial * n_1 * (n_1-1)

Unfortunately however that will fail on the first pass when n_1 is 1, so you'll need something like

if (i>1) n_factorial = n_factorial * n_1 * (n_1-1)

4. Sep 15, 2011

### mattmac.nuke

Thank you Uart! I suspected that might have been the problem, but I was entirely blanking on how to correct it. In my text book they only had one example of a factorial function calculator, but I was stumped on how to transpose that code into one which handles the cases where 'i' is multiplied by a number, or when a number is subtracted from it.

And to Rcgldr, originally my idea was to allow the user to input various integer values for n, but I think now I'll add a condition something like, IF (abs(sin(x)-sin_x) < 1E-6) EXIT. I think it should run until the condition is satisfied...

5. Sep 15, 2011

### rcgldr

An alternative would be to update n_factorial twice, once before and once after it's used:

n_factorial = n_factorial * n_1

sum_1 = (((-1)**(i-1)) * ((x**((2*i) - 1))/(n_factorial)))

sin_x = sin_x + sum_1

n_factorial = n_factorial * (n_1 +1 )

You're currrent method is fine, I was just wondering what values you were trying for n. Sorry I missed the n_factorial issue, it was late and I wasn't paying attention to the rest of the code.