Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active October 12, 2022 17:00
Show Gist options
  • Save komasaru/f1e76fc44cd650298e2e9485620533ed to your computer and use it in GitHub Desktop.
Save komasaru/f1e76fc44cd650298e2e9485620533ed to your computer and use it in GitHub Desktop.
Fortran 95 source code to compute a simple linear regression line.
!****************************************************
! 単回帰直線計算
!
! date name version
! 2018.12.18 mk-mode.com 1.00 新規作成
!
! Copyright(C) 2018 mk-mode.com All Rights Reserved.
!****************************************************
!
module const
! SP: 単精度(4), DP: 倍精度(8)
integer, parameter :: SP = kind(1.0)
integer(SP), parameter :: DP = selected_real_kind(2 * precision(1.0_SP))
end module const
module comp
use const
implicit none
private
public :: calc_reg_line
contains
! 単回帰直線計算
!
! :param(in) real(8) x(:): 説明変数配列
! :param(in) real(8) y(:): 目的変数配列
! :param(out) real(8) a: 切片
! :param(out) real(8) b: 傾き
subroutine calc_reg_line(x, y, a, b)
implicit none
real(DP), intent(in) :: x(:), y(:)
real(DP), intent(out) :: a, b
integer(SP) :: size_x, size_y, i
real(DP) :: sum_x, sum_y, sum_xx, sum_xy
size_x = size(x)
size_y = size(y)
if (size_x == 0 .or. size_y == 0) then
print *, "[ERROR] array size == 0"
stop
end if
if (size_x /= size_y) then
print *, "[ERROR] size(X) != size(Y)"
stop
end if
sum_x = sum(x)
sum_y = sum(y)
sum_xx = sum(x * x)
sum_xy = sum(x * y)
a = (sum_xx * sum_y - sum_xy * sum_x) &
& / (size_x * sum_xx - sum_x * sum_x)
b = (size_x * sum_xy - sum_x * sum_y) &
& / (size_x * sum_xx - sum_x * sum_x)
end subroutine calc_reg_line
end module comp
program regression_line
use const
use comp
implicit none
real(DP) :: x(10), y(10), a, b
x = (/107, 336, 233, 82, 61, 378, 129, 313, 142, 428/)
y = (/286, 851, 589, 389, 158, 1037, 463, 563, 372, 1020/)
print '(A, 10F8.2, A)', "説明変数 X = (", x, ")"
print '(A, 10F8.2, A)', "目的変数 Y = (", y, ")"
print '(A)', "---"
call calc_reg_line(x, y, a, b)
print '(A, F12.8)', "切片 a = ", a
print '(A, F12.8)', "傾き b = ", b
end program regression_line
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment