How to implement factorial function into code?

笑着哭i 提交于 2019-12-14 02:05:49

问题


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.


回答1:


You do NOT want to use a factorial function for your Taylor series. That would meant computing the same terms over and over. You should just multiply the factorial variable in each loop iteration. Don't forget to use real because the integer will overflow quickly.

See the answer under the question of your schoolmate Program For Calculating Sin Using Taylor Expansion Not Working?




回答2:


The following simple function answers your question. Note how it returns a real, not an integer. If performance is not an issue, then this is fine for the Taylor series.

real function fact(n)
  integer, intent(in) :: n

  integer :: i

  if (n < 0) error stop 'factorial is singular for negative integers'
  fact = 1.0
  do i = 2, n
    fact = fact * i
  enddo
end function fact

But the real answer is that Fortran 2008 does have an intrinsic function for the factorial: the Gamma function. For a positive integer n, it is defined such that Gamma(n+1) == fact(n).

(I can imagine the Gamma function is unfamiliar. It's a generalization of the factorial function: Gamma(x) is defined for all complex x, except non-positive integers. The offset in the definition is for historical reasons and unnecessarily confusing it you ask me.)




回答3:


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.




回答4:


Can you write the equation which gives factorial? It may look something like this

PURE FUNCTION Bang(N)
IMPLICIT NONE
INTEGER, INTENT(IN) :: N
INTEGER             :: I
INTEGER             :: Bang

Bang = N
IF(N == 2) THEN
  Bang = 2
ELSEIF(N == 1) THEN
  Bang = 1
ELSEIF(N < 1) THEN
  WRITE(*,*)'Error in Bang function N=',N
  STOP
ELSE
  DO I = (N-1), 2, -1
    Bang = Bang * I
  ENDDO
ENDIF

RETURN
END FUNCTION Bang


来源:https://stackoverflow.com/questions/45645815/how-to-implement-factorial-function-into-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!