超简单的Erlang复数实现

本文介绍了一个用Erlang实现复数运算的简单模块,包括加法、减法、乘法和除法等基本运算,并提供了获取实部和虚部的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

% 超简单的复数的Erlang实现
% 参见:  http://www.trapexit.org/Complex_Numbers
-module(complex).
-export([make/2, is_complex/1, add/2, sub/2, mult/2, divide/2,
         get_real/1, get_imaginary/1]).
-record( complex, {real, imaginary}).
is_complex(X) when is_record(X, complex) -> true;
is_complex(_) -> false.
make(Real, Imaginary) ->
    #complex{real = Real, imaginary = Imaginary}.
make(X) when is_record(X, complex) -> X;
make(Real) -> make(Real, 0).
add(X, Y) ->
    A = make(X), B = make(Y),
    make( A#complex.real      + B#complex.real,
          A#complex.imaginary + B#complex.imaginary).
sub(X, Y) ->
    A = make(X), B = make(Y),
    make( A#complex.real      - A#complex.real,
          B#complex.imaginary - B#complex.imaginary).
mult(X, Y) ->
    A = make(X), B = make(Y),
    make( (A#complex.real * B#complex.real)
              - (A#complex.imaginary * B#complex.imaginary),
          (A#complex.real * B#complex.imaginary)
              + (B#complex.real * A#complex.imaginary) ).
divide(X,Y) ->
    A = make(X), B = make(Y),
    Divisor = math:pow(B#complex.real,2) + math:pow(B#complex.imaginary,2),
    make( ((A#complex.real * B#complex.real)
            + (A#complex.imaginary * B#complex.imaginary)) / Divisor,
          ((A#complex.imaginary * B#complex.real)
            - (A#complex.real * B#complex.imaginary)) / Divisor).
get_real(X) -> X#complex.real.
get_imaginary(X) -> X#complex.imaginary.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值