How to implement factorial function into code?

Viewed 11473

So I am using the taylor series to calculate sin(0.75) in fortran 90 up until a certain point, so I need to run it in a do while loop (until my condition is met). This means I will need to use a factorial, here's my code:

program taylor
implicit none
real :: x = 0.75  
real :: y
integer :: i = 3
do while (abs(y - sin(0.75)) > 10.00**(-7)) 
 i = i + 2
 y = x - ((x**i)/fact(i))
 print *, y
end do
end program taylor

Where i've written fact(i) is where i'll need the factorial. Unfortunately, Fortran doesn't have an intrinsic ! function. How would I implement the function in this program?

Thanks.

4 Answers

Here's another method to compute n! in one line using only inline functions:

product((/(i,i=1,n)/))

Of course i must be declared as an integer beforehand. It creates an array that goes from 1 to n and takes the product of all components. Bonus: It even works gives the correct thing for n = 0.

Related