Napriklad, takto to funguje s tymi quaternionmi:
quaternions.f95
module my_quaternions
type quaternion
real :: x, y, z, t
end type quaternion
interface assignment(=)
module procedure quaternion_from_array
end interface
interface operator(+)
module procedure add_quaternions
end interface
interface operator(-)
module procedure substract_quaternions
end interface
interface operator(*)
module procedure hamilton_product
end interface
contains
subroutine quaternion_from_array(q, v)
! construct quaternion Q from an array V
! Q = V
real, dimension(4), intent(in) :: v
type(quaternion), intent(out) :: q
q%x = v(1)
q%y = v(2)
q%z = v(3)
q%t = v(4)
end subroutine quaternion_from_array
subroutine print_quaternion(q, q_name)
type(quaternion), intent(in) :: q
character(*), intent(in) :: q_name
write (*, 10) q_name,' = (', q%x, ', ', q%y, ', ', q%z, ', ', q%t, ')'
write (*,*)
10 format(a, a, f8.2, a, f8.2, a, f8.2, a, f8.2, a)
end subroutine print_quaternion
function add_quaternions(a, b) result(c)
type(quaternion), intent(in) :: a
type(quaternion), intent(in) :: b
type(quaternion) :: c
c%x = a%x + b%x
c%y = a%y + b%y
c%z = a%z + b%z
c%t = a%t + b%t
end function add_quaternions
function substract_quaternions(a, b) result(c)
type(quaternion), intent(in) :: a, b
type(quaternion) :: c
c%x = a%x - b%x
c%y = a%y - b%y
c%z = a%z - b%z
c%t = a%t - b%t
end function substract_quaternions
function hamilton_product(a, b) result(c)
type(quaternion), intent(in) :: a, b
type(quaternion) :: c
c%x = a%x*b%x - a%y*b%y - a%z*b%z - a%t*b%t
c%y = a%x*b%y + a%y*b%x + a%z*b%t - a%t*b%z
c%z = a%x*b%z - a%y*b%t + a%z*b%x - a%t*b%y
c%t = a%x*b%t + a%y*b%z - a%z*b%y + a%t*b%x
end function hamilton_product
end module my_quaternions
program quaternions
use my_quaternions
type(quaternion) :: a, b, c
write (*,'(a)') 'Quaternions example:'
b = (/1., 2., 3., 4./)
a = (/5., 6., 7., 8./)
call print_quaternion(a, 'a')
call print_quaternion(b, 'b')
write (*,'(a)') 'c = a + b'
c = a + b
call print_quaternion(c, 'c')
write (*,'(a)') 'c = a - b'
c = a - b
call print_quaternion(c, 'c')
write (*,'(a)') 'c = a * b'
c = a * b
call print_quaternion(c, 'c')
end program quaternions
Output:
$ gfortran quaternions.f95 -o quaternions
$ ./quaternions
Quaternions example:
a = ( 5.00, 6.00, 7.00, 8.00)
b = ( 1.00, 2.00, 3.00, 4.00)
c = a + b
c = ( 6.00, 8.00, 10.00, 12.00)
c = a - b
c = ( 4.00, 4.00, 4.00, 4.00)
c = a * b
c = ( -60.00, 20.00, -18.00, 32.00)