簡體   English   中英

Fortran中曲線的弧長

[英]arc length of a curve in Fortran

程序必須計算x=1/2x=3/2 ƒ=3.1*x^2-5.3/x之間的ƒ=3.1*x^2-5.3/x曲線的長度。長度應計算為以n=1開頭的n條線段的總和n=1 ,以n=20結尾。

我真的找不到為什么我得到的結果是錯誤的。 例如,如果x1=1/2x2=3/2那么當我應該是13時我得到110,我給你下面的代碼:

program pr2_ex2
  implicit none

  integer::x
  double precision::dy,dx !dy=the height of the linear part & dx=the lenght of the linear part
  double precision::x1,x2,s !f=f(x) the function,x=the values which can be given to f
  double precision::length 

  print*,"Please enter the function's starting point"
  read*,x1

  print*,"Please enter the function's ending  point"
  read*,x2

  length = 0
  s = 0

  do x = 2, 21
    dx = ((x*abs(x2-x1)-(x-1)*abs(x2-x1))/(20))
    dy = (3.1*(x*abs(x2-x1)/20)**2-(5.3*20/x*abs(x2-x1)))-(3.1*((x-1)*abs(x2-x1)/20)**2-(5.3*20/(x-1)*abs(x2-x1)))

    length = sqrt((dx**2)+(dy**2))
    s = length+s
   end do

   print*,s

end program

當你面對涉及功能有問題,那么請, 創建一個函數。 它將無疑使生活變得更加輕松!

它可以幫助您進行調試,因為您可以立即找出函數是否確實進行了正確的計算。

您的代碼有很多問題,您正在混合使用整數和實數,但絕對不要這樣做。 最終會給您帶來問題。 理想情況下,應使用selected_real_kind及其關聯的精度名稱0._dp0._sp或您將要命名的精度進行定義。

這是計算段長度並產生剛好高於13的代碼。

program pr2_ex2
  implicit none
  integer, parameter :: dp = selected_real_kind(p=15)

  integer :: i
  double precision :: dy, dx, dxsq
  double precision :: x1, x2, s, x
  double precision :: length

  integer :: N 

  ! perhaps read in N as well?
  N = 20

  print*,"Please enter the function's starting point"
  !  read*,x1
  x1 = 0.5_dp
  print*,"Please enter the function's ending  point"
  ! read*,x2
  x2 = 1.5_dp

  ! are you allowed to have x2 < x1, if so abort?
  ! dx is always the same, so why calculate it all the time?
  dx = abs(x2 - x1) / real(N,dp)
  ! we need not calculate this all the time
  dxsq = dx ** 2

  ! Total length
  length = 0._dp
  do i = 1 , N 

     ! starting x of this segment
     x = x1 + dx * (i-1)

     ! Get current delta-y
     dy = f(x + dx) - f(x)

     ! calculate segment vector length
     s = sqrt(dxsq + dy ** 2)

     ! sum total length
     length = length + s

  end do

  print*,length

contains

  function f(x) result(y)
    double precision, intent(in) :: x
    double precision :: y

    y = 3.1_dp * x ** 2 - 5.3_dp / x

  end function f

end program pr2_ex2

最重要的是,編碼並不一定總是直接在實現中進行,但是上面的代碼很清楚,由於每行最多只能執行一些操作,因此您很容易發現引入的任何錯誤,請嘗試並堅持使用此方法,它將絕對會在以后幫助您...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM