* Mathematica 로 연습해본 복소수 계산 (PDF 파일로 저장한 것)



* Octave 로 연습해본 복소수 계산 (허수 단위는 기호 j 로 표현)
octave-3.4.0:1> abs(1+2j)
ans =  2.2361
octave-3.4.0:2> log(1+2j)
ans =  0.80472 + 1.10715i
octave-3.4.0:3> log(-1+2j)
ans =  0.80472 + 2.03444i
octave-3.4.0:4> log(-1-2j)
ans =  0.80472 - 2.03444i
octave-3.4.0:5> arg(1+2j)                           
ans =  1.1071
octave-3.4.0:6> arg(1+-2j)
ans = -1.1071
octave-3.4.0:7> arg(-1+-2j)
ans = -2.0344
octave-3.4.0:8> arg(-1-2j) 
ans = -2.0344
octave-3.4.0:9> arg(-1+2j)
ans =  2.0344
octave-3.4.0:10> (1+2J)*exp(pi j/2)
parse error:

  syntax error

>>> (1+2J)*exp(pi j/2)
                  ^

octave-3.4.0:10> pi
ans =  3.1416
octave-3.4.0:11> j
ans =  0 + 1i
octave-3.4.0:12> pi j
error: pi: invalid data type specified
octave-3.4.0:12> (1+2J)*exp(pi* j/2)
ans = -2.0000 + 1.0000i
octave-3.4.0:13> (1+2J)^2           
ans = -3 + 4i
octave-3.4.0:14> (1+2J)^3
ans = -11 -  2i
octave-3.4.0:15> (1+2J)**2
ans = -3 + 4i
octave-3.4.0:16> (1+2J)**3
ans = -11 -  2i
octave-3.4.0:17>                                                               




* C++ 언어로 작성된 복소수 계산 예제
/**
 * Filename TestComplex.cpp
 *
 *      Purpose: Calculate complex numbers.
 *
 *  With VC++
 *      Compile: cl TestComplex.cpp /EHsc
 *      Execute: TestComplex
 *
 *  With g++
 *      Compile: g++ TestComplex.cpp -o TestComplex
 *      Execute: ./TestComplex
 *
 *  Date: 2011. 10. 8 (Sat)
 */

#include <iostream>
#include <cstring>
#include <cmath>
#include <complex>
using namespace std;

void printComplex(const char *msg, const complex<long double> &cx) {
    if (msg != NULL && strlen(msg) > 0) {
        cout << msg;
    }
    if (cx.imag() == 0)
        cout << cx.real() << endl;
    else
        cout << "(" << cx.real() << " + " << cx.imag() << "j)" << endl;
}

complex<long double> operator*(long double n, const complex<long double> &z) {
     double x = n*z.real();
     double y = n*z.imag();
     complex<long double> tmp(x, y);
     return tmp;
}

complex<long double> operator*(const complex<long double> &z, long double n) {
     double x = n*z.real();
     double y = n*z.imag();
     complex<long double> tmp(x, y);
     return tmp;
}

complex<long double> operator/(long double n, const complex<long double> &z) {
     double sq = z.real()*z.real() + z.imag()*z.imag();
     double x = n*z.real()/sq;
     double y = -n*z.imag()/sq;
     complex<long double> tmp(x, y);
     return tmp;
}

complex<long double> operator/(const complex<long double> &z, long double n) {
     double x = z.real()/n;
     double y = z.imag()/n;
     complex<long double> tmp(x, y);
     return tmp;
}

complex<long double> operator+(const complex<long double> &z, long double n) {
     double x = z.real() + n;
     double y = z.imag();
     complex<long double> tmp(x, y);
     return tmp;
}

complex<long double> operator+(long double n, const complex<long double> &z) {
     double x = z.real() + n;
     double y = z.imag();
     complex<long double> tmp(x, y);
     return tmp;
}

complex<long double> operator-(const complex<long double> &z, long double n) {
     double x = z.real() - n;
     double y = z.imag();
     complex<long double> tmp(x, y);
     return tmp;
}

complex<long double> operator-(long double n, const complex<long double> &z) {
     double x = n - z.real();
     double y = -z.imag();
     complex<long double> tmp(x, y);
     return tmp;
}

complex<long double> operator^(const complex<long double> &z, long double n) {
     return exp(n*log(z));
}

complex<long double> operator^(long double n, const complex<long double> &z) {
     return exp(z*log(n));
}

bool operator==(const complex<long double> &z, long n) {
     return z.real() == n && z.imag() == 0;
}

bool operator==(long n, const complex<long double> &z) {
     return z.real() == n && z.imag() == 0;
}

complex<long double> sec(const complex<long double> &z) {
     return 1/cos(z);
}

complex<long double> csc(const complex<long double> &z) {
     return 1/sin(z);
}

complex<long double> cot(const complex<long double> &z) {
     return cos(z)/sin(z);
}

complex<long double> sech(const complex<long double> &z) {
     return 1/cosh(z);
}

complex<long double> csch(const complex<long double> &z) {
     return 1/sinh(z);
}

complex<long double> coth(const complex<long double> &z) {
     return cosh(z)/sinh(z);
}

complex<long double> cbrt(const complex<long double> &z) {
     /*
     double x = z.real();
     double y = z.imag();
     double r = pow(x*x + y*y, 1.0/(2*3));
     double ang = atan(y/x) / 3.0;
     complex<long double> tmp(r*cos(ang), r*sin(ang));
     return tmp;
     */
     return z^(1.0/3);
}

complex<long double> square(const complex<long double> &z) {
    return z*z;
}

complex<long double> cube(const complex<long double> &z) {
    return z*z*z;
}

int main() {
    complex<long double> a(1, 2);
    printComplex("a = ", a);

    complex<long double> b(5, 4);
    printComplex("b = ", b);

    complex<long double> c = a + b;
    printComplex("c = a + b = ", c);

    c = a - b;
    printComplex("c = a - b = ", c);

    c = a * b;
    printComplex("c = a * b = ", c);

    c = a / b;
    printComplex("c = a / b = ", c);

    c = a^2;
    printComplex("c = a^2 = ", c);

    printComplex("a^3 = ", a^3);
    printComplex("a^-3 = ", a^-3);

    printComplex("b = ", b);
    printComplex("1/(-b) = ", 1/(-b));
    printComplex("-b^-1 = ", -b^-1);
    printComplex("-b^-3 = ", -b^-3);
    printComplex("b/2 = ", b/2);

    printComplex("a = ", a);
    printComplex("a + 1 = ", a + 1);
    printComplex("b - 2 = ", b - 2);
    printComplex("2 - b = ", 2 - b);
    printComplex("b - b = ", b - b);
    cout << "b - b == 0 ? " << (b - b == 0) << endl;
    complex<long double> t(b.real(), b.imag());

    printComplex("b = ", b);
    printComplex("t = ", t);
    cout << "b == t ? " << (b == t) << endl;

    printComplex("a = ", a);
    printComplex("sin(a) = ", sin(a));
    printComplex("cos(a) = ", cos(a));
    printComplex("tan(a) = ", tan(a));
    printComplex("sec(a) = 1/cos(a) = ", sec(a));
    printComplex("csc(a) = 1/sin(a) = ", csc(a));
    printComplex("cot(a) = 1/tan(a) = ", cot(a));
    printComplex("sinh(a) = ", sinh(a));
    printComplex("cosh(a) = ", cosh(a));
    printComplex("tanh(a) = ", tanh(a));
    printComplex("sech(a) = 1/cosh(a) = ", sech(a));
    printComplex("csch(a) = 1/sinh(a) = ", csch(a));
    printComplex("coth(a) = 1/tanh(a) = ", coth(a));

    printComplex("exp(a) = ", exp(a));
    printComplex("log(a) = ", log(a));
    printComplex("norm(a) = ", norm(a));
    printComplex("abs(a) = ", abs(a));
    printComplex("2^a = ", 2^a);
    printComplex("3^a = ", 3^a);
    printComplex("sqrt(a) = ", sqrt(a));
    printComplex("cbrt(a) = ", cbrt(a));
    printComplex("square(a) = ", square(a));
    printComplex("cube(a) = ", cube(a));

    return 0;
}

/*
a = (1 + 2j)
b = (5 + 4j)
c = a + b = (6 + 6j)
c = a - b = (-4 + -2j)
c = a * b = (-3 + 14j)
c = a / b = (0.317073 + 0.146341j)
c = a^2 = (-3 + 4j)
a^3 = (-11 + -2j)
a^-3 = (-0.088 + 0.016j)
b = (5 + 4j)
1/(-b) = (-0.121951 + 0.097561j)
-b^-1 = (-0.121951 + 0.097561j)
-b^-3 = (0.00166858 + 0.00342421j)
b/2 = (2.5 + 2j)
a = (1 + 2j)
a + 1 = (2 + 2j)
b - 2 = (3 + 4j)
2 - b = (-3 + -4j)
b - b = 0
b - b == 0 ? 1
b = (5 + 4j)
t = (5 + 4j)
b == t ? 1
a = (1 + 2j)
sin(a) = (3.16578 + 1.9596j)
cos(a) = (2.03272 + -3.0519j)
tan(a) = (0.0338128 + 1.01479j)
sec(a) = 1/cos(a) = (0.151176 + 0.226974j)
csc(a) = 1/sin(a) = (0.228375 + -0.141363j)
cot(a) = 1/tan(a) = (0.0327978 + -0.984329j)
sinh(a) = (-0.489056 + 1.40312j)
cosh(a) = (-0.642148 + 1.06861j)
tanh(a) = (1.16674 + -0.243458j)
sech(a) = 1/cosh(a) = (-0.413149 + -0.687527j)
csch(a) = 1/sinh(a) = (-0.221501 + -0.635494j)
coth(a) = 1/tanh(a) = (0.82133 + 0.171384j)
exp(a) = (-1.1312 + 2.47173j)
log(a) = (0.804719 + 1.10715j)
norm(a) = 5
abs(a) = 2.23607
2^a = (0.366914 + 1.96606j)
3^a = (-1.75876 + 2.43038j)
sqrt(a) = (1.27202 + 0.786151j)
cbrt(a) = (1.21962 + 0.471711j)
square(a) = (-3 + 4j)
cube(a) = (-11 + -2j)
*/





* Groovy 언어로 작성된 Complex 클래스의 소스 (Java 에서도 사용 가능한 클래스)
   (참고: Groovy 1.8.0 과 Java 7 에서 테스트되었음)
/**********************************************************************************
 * Filename: Complex.groovy
 *
 *  Purpose:
 *           A class, supporting complex calculations,
 *           which depends on the double types of Java.
 *
 *  Setting Environment Variables:
 *           set JAVA_HOME=c:\Java7
 *           set GROOVY_HOME=c:\groovy182
 *           set PATH=c:%GROOVY_HOME%\bin;%PATH%
 *
 *  Execute Only: groovy Complex.groovy
 *  Compile for Java: groovyc -d . Complex.groovy
 *
 *    Author: Copyright (c) 2011. 10. 7 (Fri)  PH Kim  ( pkim (AT) scripts (DOT) pe (DOT) kr )
 ***********************************************************************************/

package kr.pe.scripts.numeric.complex

public class Complex {

    public double re;
    public double im;
    final public static double EPS = 9.0E-16;
    final public static Complex ZERO = new Complex(0, 0);
    final public static Complex ONE = new Complex(1, 0);
    final public static Complex TWO = new Complex(2, 0);
    final public static Complex THREE = new Complex(3, 0);
    final public static Complex TEN = new Complex(10, 0);
    final public static Complex I = new Complex(0, 1);
    final public static Complex E = new Complex(Math.E, 0);
    final public static Complex PI = new Complex(Math.PI, 0);

    public Complex(double x, double y) {
        this.re = x;
        this.im = y;
    }

    public static Complex polarForm(double r, double theta) {
        double x = r*Math.cos(theta);
        double y = r*Math.sin(theta);
        Complex z = new Complex(x, y);
        adjust(z);
        return z;
    }

    public boolean isZero() {
         // return this.re == 0.0 && this.im == 0.0;
         return Math.abs(this.re*this.re + this.im*this.im) < EPS
    }

    public Complex plus(Complex other) {
         return new Complex(this.re + other.re, this.im + other.im);
    }

    public Complex minus(Complex other) {
         return new Complex(this.re - other.re, this.im - other.im);
    }

    public Complex multiply(Complex other) {
         double x = this.re*other.re - this.im*other.im;
         double y = this.re*other.im + this.im*other.re;
         return new Complex(x, y);
    }

    public Complex div(Complex other) {
         if (other.isZero()) {
             throw new RuntimeException("Cannot divide by " + other + ", since it is zero.");
         }
         double x = this.re*other.re + this.im*other.im;
         double y = - this.re*other.im + this.im*other.re;
         double tmp = other.re*other.re + other.im*other.im;
         return new Complex(x/tmp, y/tmp);
    }

    /*
    public Complex power(long n) {
         long mn = n;
         if (mn < 0.0)
             mn = -mn;
         Complex tmp = new Complex(1, 0);
         for (int i = 0; i < mn; i++) {
             tmp = tmp*this;
         }
         if (n < 0) {
             tmp = new Complex(1, 0) / tmp;
         }
         return tmp;
    }
    */

    public Complex power(long n) {
         if (n == 0)
             return new Complex(1, 0);
         long mn = n;
         if (mn < 0L)
             mn = -mn;
         Complex tmp = this.power((mn/2) as long);
         if (mn % 2 == 1) {
             tmp = tmp*tmp*this;
         }
         else {
             tmp = tmp*tmp;
         }
         if (n < 0) {
             tmp = Complex.ONE / tmp;
         }
         return tmp;
    }

    public Complex power(double x) {
         if (x == 0.0)
             return new Complex(1, 0);
         return exp(new Complex(x, 0)*log(this));
    }

    public Complex power(Complex other) {
         if (other.isZero())
             return new Complex(1, 0);
         return exp(other*log(this));
    }

    public static Complex sqrt(Complex z) {
         if (z.isZero())
             return new Complex(0, 0);
         double r = Math.sqrt(abs(z));
         double angle = arg(z) / 2.0;
         double x = r*Math.cos(angle);
         double y = r*Math.sin(angle);
         return new Complex(x, y);
    }

    public static Complex cbrt(Complex z) {
         if (z.isZero())
             return new Complex(0, 0);
         double r = Math.cbrt(abs(z));
         double angle = arg(z)/3.0;
         double x = r*Math.cos(angle);
         double y = r*Math.sin(angle);
         return new Complex(x, y);
    }

    public static Complex square(Complex z) {
         return z*z;
    }

    public static Complex cube(Complex z) {
         return z*z*z;
    }

    public Complex inverse() {
          return new Complex(1, 0) / this;
    }

    public double abs() {
        double x = this.re;
        double y = this.im;
        return Math.sqrt(x*x + y*y);
    }

    public double norm() {
        double x = this.re;
        double y = this.im;
        return Math.sqrt(x*x + y*y);
    }

    public double distance(Complex other) {
        double x = this.re - other.re;
        double y = this.im - other.im;
        return Math.sqrt(x*x + y*y);
    }

    public static double abs(Complex z) {
        double x = z.re;
        double y = z.im;
        return Math.sqrt(x*x + y*y);
    }

    public static double norm(Complex z) {
        double x = z.re;
        double y = z.im;
        return Math.sqrt(x*x + y*y);
    }

    public static double distance(Complex z, Complex w) {
        double x = z.re - w.re;
        double y = z.im - w.im;
        return Math.sqrt(x*x + y*y);
    }

    public static Complex innerProduct(Complex z, Complex w) {
        return conjugate(z)*w;
    }

    public Complex innerProduct(Complex other) {
        return this.conjugate()*other;
    }

    public static boolean isOrthogonal(Complex z, Complex w) {
        // return z.re*w.re + z.im*w.im == 0.0;
        return Math.abs(z.re*w.re + z.im*w.im) < EPS;
    }

    public boolean isOrthogonal(Complex other) {
        // return this.re*other.re + this.im*other.im == 0.0;
        return Math.abs(this.re*other.re + this.im*other.im) < EPS;
    }

    public static double angleCosine(Complex z, Complex w) {
        return (z.re*w.re + z.im*w.im)/(Math.sqrt(z.re*z.re + z.im*z.im) * Math.sqrt(w.re*w.re + w.im*w.im));
    }

    public angleCosine(Complex other) {
        return (this.re*other.re + this.im*other.im)/(Math.sqrt(this.re*this.re + this.im*this.im) * Math.sqrt(other.re*other.re + other.im*other.im));
    }

    public static double angle(Complex z, Complex w) {
        return 180.0 / Math.PI * Math.acos((z.re*w.re + z.im*w.im)/(Math.sqrt(z.re*z.re + z.im*z.im) * Math.sqrt(w.re*w.re + w.im*w.im)));
    }

    public double angle(Complex other) {
        return 180.0 / Math.PI * Math.acos((this.re*other.re + this.im*other.im)/(Math.sqrt(this.re*this.re + this.im*this.im) * Math.sqrt(other.re*other.re + other.im*other.im)));
    }

    public Complex negative() {
        return new Complex(-this.re, -this.im);
    }

    public Complex conjugate() {
        return new Complex(this.re, -this.im);
    }

    public static Complex conjugate(Complex z) {
        return new Complex(z.re, -z.im);
    }

    public static Complex exp(Complex z) {
        double x, y;
        x = Math.exp(z.re)*Math.cos(z.im);
        y = Math.exp(z.re)*Math.sin(z.im);
        return new Complex(x, y);
    }

    public static Complex log(Complex z) {
        double x, y;
        x = Math.log(abs(z));
        if (z.re == 0.0) {
            if (z.im > 0.0)
                y = Math.PI/2;
            else if (z.im < 0.0)
                y = -Math.PI/2;
            else
                throw new RuntimeException("log(" + z + ") cannot be evaulated.");
        }
        else {
            y = Math.atan(z.im/z.re);
            if (z.re < 0) {
                if (z.im >= 0)
                    y = y + Math.PI;
                else
                    y = y - Math.PI;
            }
        }
        return new Complex(x, y);
    }

    public double arg() {
        double y;
        if (this.re == 0.0) {
            if (this.im > 0.0)
                y = Math.PI/2;
            else if (this.im < 0.0)
                y = -Math.PI/2;
            else
                throw new RuntimeException("arg(" + this + ") cannot be evaulated.");
        }
        else {
            y = Math.atan(this.im/this.re);
            if (this.re < 0) {
                if (this.im >= 0)
                    y = y + Math.PI;
                else
                    y = y - Math.PI;
            }
        }
        return y;
    }

    public static double arg(Complex z) {
        double y;
        if (z.re == 0.0) {
            if (z.im > 0.0)
                y = Math.PI/2;
            else if (z.im < 0.0)
                y = -Math.PI/2;
            else
                throw new RuntimeException("arg(" + z + ") cannot be evaulated.");
        }
        else {
            y = Math.atan(z.im/z.re);
            if (z.re < 0) {
                if (z.im >= 0)
                    y = y + Math.PI;
                else
                    y = y - Math.PI;
            }
        }
        return y;
    }

    public static Complex sin(Complex z) {
        double x, y;
        x = Math.sin(z.re)*Math.cosh(z.im);
        y = Math.cos(z.re)*Math.sinh(z.im);
        return new Complex(x, y);
    }

    public static Complex cos(Complex z) {
        double x, y;
        x = Math.cos(z.re)*Math.cosh(z.im);
        y = -Math.sin(z.re)*Math.sinh(z.im);
        return new Complex(x, y);
    }

    public static Complex tan(Complex z) {
        Complex a = cos(z);
        if (a.isZero()) {
            throw new RuntimeException("tan(" + z + ") cannot be evaulated, since cos(" + z + ") = 0.");
        }
        Complex b = sin(z);
        return b/a;
    }

    public static Complex sec(Complex z) {
        Complex a = cos(z);
        if (a.isZero()) {
            throw new RuntimeException("sec(" + z + ") cannot be evaulated, since cos(" + z + ") = 0.");
        }
        return ONE/a;
    }

    public static Complex csc(Complex z) {
        Complex a = sin(z);
        if (a.isZero()) {
            throw new RuntimeException("csc(" + z + ") cannot be evaulated, since sin(" + z + ") = 0.");
        }
        return ONE/a;
    }

    public static Complex cot(Complex z) {
        Complex a = sin(z);
        if (a.isZero()) {
            throw new RuntimeException("tan(" + z + ") cannot be evaulated, since sin(" + z + ") = 0.");
        }
        Complex b = cos(z);
        return b/a;
    }

    public static Complex sinh(Complex z) {
        Complex a = exp(z);
        return (a - a.inverse())/TWO;
    }

    public static Complex cosh(Complex z) {
        Complex a = exp(z);
        return (a + a.inverse())/TWO;
    }

    public static Complex tanh(Complex z) {
        Complex a = cosh(z);
        if (a.isZero()) {
            throw new RuntimeException("tanh(" + z + ") cannot be evaulated, since cosh(" + z + ") = 0.");
        }
        Complex b = sinh(z);
        return b/a;
    }

    public static Complex sech(Complex z) {
        Complex a = cosh(z);
        if (a.isZero()) {
            throw new RuntimeException("sech(" + z + ") cannot be evaulated, since cosh(" + z + ") = 0.");
        }
        return ONE/a;
    }

    public static Complex csch(Complex z) {
        Complex a = sinh(z);
        if (a.isZero()) {
            throw new RuntimeException("csch(" + z + ") cannot be evaulated, since sinh(" + z + ") = 0.");
        }
        return ONE/a;
    }

    public static Complex coth(Complex z) {
        Complex a = sinh(z);
        if (a.isZero()) {
            throw new RuntimeException("coth(" + z + ") cannot be evaulated, since sinh(" + z + ") = 0.");
        }
        Complex b = cosh(z);
        return b/a;
    }

    public boolean equals(Complex other) {
        // return this.re == other.re && this.im == other.im;
        double x = this.re - other.re;
        double y = this.re - other.re;
        return Math.sqrt(x*x + y*y) < EPS;
    }

    public Complex rotate(double deg) {
        return this*exp(new Complex(0, deg*Math.PI/180.0));
    }

    public static void adjust(Complex z) {
        if (Math.abs(z.re) < EPS)
            z.re = 0.0;
        if (Math.abs(z.im) < EPS)
            z.im = 0.0;
    }

    public void adjust() {
        if (Math.abs(this.re) < EPS)
            this.re = 0.0;
        if (Math.abs(this.im) < EPS)
            this.im = 0.0;
    }

    public String toString() {
        return "(" + this.re + " + " + this.im + "j)";
    }

    public static void println(String s) {
        System.out.println(s);
    }

    public static void main(String[] args) {
        Complex z = new Complex(1, 2);
        Complex w = new Complex(5, 4);
        println("z = " + z);
        println("w = " + w);
        println("    z + w = " + (z + w));
        println("    z - w = " + (z - w));
        println("    z * w = " + (z * w));
        println("    z / w = " + (z / w));
        println("    z**2 = " + (z**2));
        println("    z**3 = " + (z**3));
        println("    z.inverse() = " + z.inverse());
        println("    z**-1 = " + (z**-1));
        println("    z**-2 = " + (z**-2));
        println("    z**-3 = " + (z**-3));
        println("    -z = " + (-z));
        println("    conjugate(z) = conjugate(" + z + ") = " + conjugate(z));
        println("    z.conjugate() = (" + z + ").conjuate() = " + z.conjugate());
        println("    abs(z) = abs(" + z + ") = " + abs(z));
        println("    norm(z) = norm(" + z + ") = " + norm(z));
        println("    z.abs() = (" + z + ").abs() = " + z.abs());
        println("    z.norm() = (" + z + ").norm() = " + z.norm());
        println("    distance(z, w) = distance(" + z + ", " + w + ") = " + distance(z, w));
        println("    z.distance(w) = (" + z + ").distance("+ w + ") = " + z.distance(w));
        println("    exp(z) = exp(" + z + ") = " + exp(z));
        println("    log(z) = log(" + z + ") = " + log(z));
        println("    arg(z) = arg(" + z + ") = " + arg(z));
        println("    abs(" + new Complex(-1, 2)  + ") = " + abs(new Complex(-1, 2)));
        println("    log(" + new Complex(-1, 2)  + ") = " + log(new Complex(-1, 2)));
        println("    abs(" + new Complex(-1, -2)  + ") = " + abs(new Complex(-1, -2)));
        println("    log(" + new Complex(-1, -2)  + ") = " + log(new Complex(-1, -2)));
        println("    arg(" + new Complex(1, -2)  + ") = " + arg(new Complex(1, -2)));
        println("    arg(" + new Complex(-1, 2)  + ") = " + arg(new Complex(-1, 2)));
        println("    arg(" + new Complex(-1, -2)  + ") = " + arg(new Complex(-1, -2)));
        println("    sin(z) = sin(" + z + ") = " + sin(z));
        println("    cos(z) = cos(" + z + ") = " + cos(z));
        println("    tan(z) = tan(" + z + ") = " + tan(z));
        println("    sec(z) = sec(" + z + ") = " + sec(z));
        println("    csc(z) = csc(" + z + ") = " + csc(z));
        println("    cot(z) = cot(" + z + ") = " + cot(z));
        println("    sinh(z) = sinh(" + z + ") = " + sinh(z));
        println("    cosh(z) = cosh(" + z + ") = " + cosh(z));
        println("    tanh(z) = tanh(" + z + ") = " + tanh(z));
        println("    sech(z) = sech(" + z + ") = " + sech(z));
        println("    csch(z) = csch(" + z + ") = " + csch(z));
        println("    coth(z) = coth(" + z + ") = " + coth(z));
        println("    z.rotate(90) = " + z.rotate(90));
        println("    z.rotate(-90) = " + z.rotate(-90));
        println("    z == " + new Complex(1, 2) + " ? " + (z == new Complex(1,2)));
        println("    z - z = " + (z - z));
        println("    (z - z).isZero() ? " + (z - z).isZero());
        println("    Complex.ZERO = " + Complex.ZERO);
        println("    Complex.ONE = " + Complex.ONE);
        println("    Complex.TWO = " + Complex.TWO);
        println("    Complex.THREE = " + Complex.THREE);
        println("    Complex.TEN = " + Complex.TEN);
        println("    Complex.I = " + Complex.I);
        println("    Complex.E = " + Complex.E);
        println("    Complex.PI = " + Complex.PI);
        println("    z = " + z);
        println("    w = " + w);
        println("    innerProduct(z, w) = " + innerProduct(z, w));
        println("    z.innerProduct(w) = " + z.innerProduct(w));
        println("    isOrthogonal(z, w) = " + isOrthogonal(z, w));
        println("    z.isOrthogonal(w) = " + z.isOrthogonal(w));
        println("    z.innerProduct(z.rotate(90)) = " + z.innerProduct(z.rotate(90)));
        println("    isOrthogonal(z, z.rotate(90))= " + isOrthogonal(z, z.rotate(90)));
        println("    z.isOrthogonal(z.rotate(90)) = " + z.isOrthogonal(z.rotate(90)));
        println("    angleCosine(z, w) = " + angleCosine(z, w));
        println("    z.angleCosine(w) = " + z.angleCosine(w));
        println("    angle(z, w) = " + angle(z, w));
        println("    z.angle(w) = " + z.angle(w));
        println("    angle(z, z.rotate(90))= " + angle(z, z.rotate(90)));
        println("    z.angle(z.rotate(90)) = " + z.angle(z.rotate(90)));
        println("    angle(z, z.rotate(-90))= " + angle(z, z.rotate(-90)));
        println("    z.angle(z.rotate(-90)) = " + z.angle(z.rotate(-90)));
        println("    I**I = " + (I**I));
        println("    TWO**I = " + (TWO**I));
        println("    THREE**I = " + (THREE**I));
        println("    TEN**I = " + (TEN**I));
        println("    I**TWO = " + (I**TWO));
        println("    I**THREE = " + (I**THREE));
        println("    I**TEN = " + (I**TEN));
        Complex u = I**TEN;
        println("    u = I**TEN = " + u);
        Complex.adjust(u);
        println("    Atfer Complex.adjust(u)");
        println("    u = " + u);
        println("    sqrt(z) = " + sqrt(z));
        println("    cbrt(z) = " + cbrt(z));
        println("    square(z) = " + square(z));
        println("    cube(z) = " + cube(z));
        println("    Complex.polarForm(1, Math.PI/2) = " + Complex.polarForm(1, Math.PI/2));
        println("    Complex.polarForm(1, Math.PI) = " + Complex.polarForm(1, Math.PI));
    }
}
/*
Execution Result:
z = (1.0 + 2.0j)
w = (5.0 + 4.0j)
    z + w = (6.0 + 6.0j)
    z - w = (-4.0 + -2.0j)
    z * w = (-3.0 + 14.0j)
    z / w = (0.3170731707317073 + 0.14634146341463414j)
    z**2 = (-3.0 + 4.0j)
    z**3 = (-11.0 + -2.0j)
    z.inverse() = (0.2 + -0.4j)
    z**-1 = (0.2 + -0.4j)
    z**-2 = (-0.12 + -0.16j)
    z**-3 = (-0.088 + 0.016j)
    -z = (-1.0 + -2.0j)
    conjugate(z) = conjugate((1.0 + 2.0j)) = (1.0 + -2.0j)
    z.conjugate() = ((1.0 + 2.0j)).conjuate() = (1.0 + -2.0j)
    abs(z) = abs((1.0 + 2.0j)) = 2.23606797749979
    norm(z) = norm((1.0 + 2.0j)) = 2.23606797749979
    z.abs() = ((1.0 + 2.0j)).abs() = 2.23606797749979
    z.norm() = ((1.0 + 2.0j)).norm() = 2.23606797749979
    distance(z, w) = distance((1.0 + 2.0j), (5.0 + 4.0j)) = 4.47213595499958
    z.distance(w) = ((1.0 + 2.0j)).distance((5.0 + 4.0j)) = 4.47213595499958
    exp(z) = exp((1.0 + 2.0j)) = (-1.1312043837568138 + 2.471726672004819j)
    log(z) = log((1.0 + 2.0j)) = (0.8047189562170503 + 1.1071487177940904j)
    arg(z) = arg((1.0 + 2.0j)) = 1.1071487177940904
    abs((-1.0 + 2.0j)) = 2.23606797749979
    log((-1.0 + 2.0j)) = (0.8047189562170503 + 2.0344439357957027j)
    abs((-1.0 + -2.0j)) = 2.23606797749979
    log((-1.0 + -2.0j)) = (0.8047189562170503 + -2.0344439357957027j)
    arg((1.0 + -2.0j)) = -1.1071487177940904
    arg((-1.0 + 2.0j)) = 2.0344439357957027
    arg((-1.0 + -2.0j)) = -2.0344439357957027
    sin(z) = sin((1.0 + 2.0j)) = (3.165778513216168 + 1.9596010414216063j)
    cos(z) = cos((1.0 + 2.0j)) = (2.0327230070196656 + -3.0518977991518j)
    tan(z) = tan((1.0 + 2.0j)) = (0.0338128260798966 + 1.0147936161466335j)
    sec(z) = sec((1.0 + 2.0j)) = (0.15117629826557724 + 0.2269736753937216j)
    csc(z) = csc((1.0 + 2.0j)) = (0.22837506559968654 + -0.1413630216124078j)
    cot(z) = cot((1.0 + 2.0j)) = (0.0327977555337525 + -0.9843292264581908j)
    sinh(z) = sinh((1.0 + 2.0j)) = (-0.48905625904129374 + 1.4031192506220407j)
    cosh(z) = cosh((1.0 + 2.0j)) = (-0.6421481247155201 + 1.0686074213827785j)
    tanh(z) = tanh((1.0 + 2.0j)) = (1.16673625724092 + -0.24345820118572523j)
    sech(z) = sech((1.0 + 2.0j)) = (-0.41314934426693994 + -0.6875274386554789j)
    csch(z) = csch((1.0 + 2.0j)) = (-0.2215009308505094 + -0.6354937992538999j)
    coth(z) = coth((1.0 + 2.0j)) = (0.8213297974938518 + 0.17138361290918502j)
    z.rotate(90) = (-2.0 + 1.0000000000000002j)
    z.rotate(-90) = (2.0 + -0.9999999999999999j)
    z == (1.0 + 2.0j) ? true
    z - z = (0.0 + 0.0j)
    (z - z).isZero() ? true
    Complex.ZERO = (0.0 + 0.0j)
    Complex.ONE = (1.0 + 0.0j)
    Complex.TWO = (2.0 + 0.0j)
    Complex.THREE = (3.0 + 0.0j)
    Complex.TEN = (10.0 + 0.0j)
    Complex.I = (0.0 + 1.0j)
    Complex.E = (2.718281828459045 + 0.0j)
    Complex.PI = (3.141592653589793 + 0.0j)
    z = (1.0 + 2.0j)
    w = (5.0 + 4.0j)
    innerProduct(z, w) = (13.0 + -6.0j)
    z.innerProduct(w) = (13.0 + -6.0j)
    isOrthogonal(z, w) = false
    z.isOrthogonal(w) = false
    z.innerProduct(z.rotate(90)) = (4.440892098500626E-16 + 5.0j)
    isOrthogonal(z, z.rotate(90))= true
    z.isOrthogonal(z.rotate(90)) = true
    angleCosine(z, w) = 0.9079593845004517
    z.angleCosine(w) = 0.9079593845004517
    angle(z, w) = 24.77514056883192
    z.angle(w) = 24.77514056883192
    angle(z, z.rotate(90))= 90.0
    z.angle(z.rotate(90)) = 90.0
    angle(z, z.rotate(-90))= 90.0
    z.angle(z.rotate(-90)) = 90.0
    I**I = (0.20787957635076193 + 0.0j)
    TWO**I = (0.7692389013639721 + 0.6389612763136348j)
    THREE**I = (0.4548324228266097 + 0.8905770416677471j)
    TEN**I = (-0.6682015101903132 + 0.7439803369574931j)
    I**TWO = (-1.0 + 1.2246467991473532E-16j)
    I**THREE = (-1.8369701987210297E-16 + -1.0j)
    I**TEN = (-1.0 + 6.123233995736766E-16j)
    u = I**TEN = (-1.0 + 6.123233995736766E-16j)
    Atfer Complex.adjust(u)
    u = (-1.0 + 0.0j)
    sqrt(z) = (1.272019649514069 + 0.7861513777574233j)
    cbrt(z) = (1.2196165079717578 + 0.47171126778938893j)
    square(z) = (-3.0 + 4.0j)
    cube(z) = (-11.0 + -2.0j)
    Complex.polarForm(1, Math.PI/2) = (0.0 + 1.0j)
    Complex.polarForm(1, Math.PI) = (-1.0 + 0.0j)
*/




* Groovy 언어로 작성된 Complex 클래스를 테스트하는 Java 예제 소스
/**********************************************************************************
 * Filename: TestComplex.java
 *
 *  Purpose:
 *           Testing the Complex class made by Groovy,
 *
 *  Setting Environment Variables:
 *           set JAVA_HOME=c:\Java7
 *           set GROOVY_HOME=c:\groovy182
 *           set PATH=c:%GROOVY_HOME%\bin;%PATH%
 *
 *  Compile: javac -d . TestComplex.java
 *  Execute: java -cp .;%GROOVY_HOME%\embeddable\groovy-all-1.8.2.jar
 *                kr.pe.scripts.numeric.complex.TestComplex
 *
 *    Author: Copyright (c) 2011. 10. 7 (Fri)  PH Kim  ( pkim (AT) scripts (DOT) pe (DOT) kr )
 ***********************************************************************************/

package kr.pe.scripts.numeric.complex;

import kr.pe.scripts.numeric.complex.Complex;

public class TestComplex {

    public static void println(String s) {
        System.out.println(s);
    }

    public static void main(String[] args) {
        Complex z = new Complex(1, 2);
        Complex w = new Complex(5, 4);
        println("z = " + z);
        println("w = " + w);
        println("    z + w = " + z.plus(w));
        println("    z - w = " + z.minus(w));
        println("    z * w = " + z.multiply(w));
        println("    z / w = " + z.div(w));
        println("    z**2 = " + z.power(2));
        println("    z**3 = " + z.power(3));
        println("    z.inverse() = " + z.inverse());
        println("    z**-1 = " + z.power(-1));
        println("    z**-2 = " + z.power(-2));
        println("    z**-3 = " + z.power(-3));
        println("    -z = " + z.negative());
        println("    conjugate(z) = conjugate(" + z + ") = " + Complex.conjugate(z));
        println("    z.conjugate() = (" + z + ").conjuate() = " + z.conjugate());
        println("    abs(z) = abs(" + z + ") = " + Complex.abs(z));
        println("    norm(z) = norm(" + z + ") = " + Complex.norm(z));
        println("    z.abs() = (" + z + ").abs() = " + z.abs());
        println("    z.norm() = (" + z + ").norm() = " + z.norm());
        println("    distance(z, w) = distance(" + z + ", " + w + ") = " + Complex.distance(z, w));
        println("    z.distance(w) = (" + z + ").distance("+ w + ") = " + z.distance(w));
        println("    exp(z) = exp(" + z + ") = " + Complex.exp(z));
        println("    log(z) = log(" + z + ") = " + Complex.log(z));
        println("    arg(z) = arg(" + z + ") = " + Complex.arg(z));
        println("    abs(" + new Complex(-1, 2)  + ") = " + Complex.abs(new Complex(-1, 2)));
        println("    log(" + new Complex(-1, 2)  + ") = " + Complex.log(new Complex(-1, 2)));
        println("    abs(" + new Complex(-1, -2)  + ") = " + Complex.abs(new Complex(-1, -2)));
        println("    log(" + new Complex(-1, -2)  + ") = " + Complex.log(new Complex(-1, -2)));
        println("    arg(" + new Complex(1, -2)  + ") = " + Complex.arg(new Complex(1, -2)));
        println("    arg(" + new Complex(-1, 2)  + ") = " + Complex.arg(new Complex(-1, 2)));
        println("    arg(" + new Complex(-1, -2)  + ") = " + Complex.arg(new Complex(-1, -2)));
        println("    sin(z) = sin(" + z + ") = " + Complex.sin(z));
        println("    cos(z) = cos(" + z + ") = " + Complex.cos(z));
        println("    tan(z) = tan(" + z + ") = " + Complex.tan(z));
        println("    sec(z) = sec(" + z + ") = " + Complex.sec(z));
        println("    csc(z) = csc(" + z + ") = " + Complex.csc(z));
        println("    cot(z) = cot(" + z + ") = " + Complex.cot(z));
        println("    sinh(z) = sinh(" + z + ") = " + Complex.sinh(z));
        println("    cosh(z) = cosh(" + z + ") = " + Complex.cosh(z));
        println("    tanh(z) = tanh(" + z + ") = " + Complex.tanh(z));
        println("    sech(z) = sech(" + z + ") = " + Complex.sech(z));
        println("    csch(z) = csch(" + z + ") = " + Complex.csch(z));
        println("    coth(z) = coth(" + z + ") = " + Complex.coth(z));
        println("    z.rotate(90) = " + z.rotate(90));
        println("    z.rotate(-90) = " + z.rotate(-90));
        // println("    z == " + new Complex(1, 2) + " ? " + (z == new Complex(1,2)));
        println("    z == " + new Complex(1, 2) + " ? " + (z.equals(new Complex(1,2))));
        println("    z - z = " + z.minus(z));
        println("    (z - z).isZero() ? " + z.minus(z).isZero());
        println("    Complex.ZERO = " + Complex.ZERO);
        println("    Complex.ONE = " + Complex.ONE);
        println("    Complex.TWO = " + Complex.TWO);
        println("    Complex.THREE = " + Complex.THREE);
        println("    Complex.TEN = " + Complex.TEN);
        println("    Complex.I = " + Complex.I);
        println("    Complex.E = " + Complex.E);
        println("    Complex.PI = " + Complex.PI);
        println("    z = " + z);
        println("    w = " + w);
        println("    innerProduct(z, w) = " + Complex.innerProduct(z, w));
        println("    z.innerProduct(w) = " + z.innerProduct(w));
        println("    isOrthogonal(z, w) = " + Complex.isOrthogonal(z, w));
        println("    z.isOrthogonal(w) = " + z.isOrthogonal(w));
        println("    z.innerProduct(z.rotate(90)) = " + z.innerProduct(z.rotate(90)));
        println("    isOrthogonal(z, z.rotate(90))= " + Complex.isOrthogonal(z, z.rotate(90)));
        println("    z.isOrthogonal(z.rotate(90)) = " + z.isOrthogonal(z.rotate(90)));
        println("    angleCosine(z, w) = " + Complex.angleCosine(z, w));
        println("    z.angleCosine(w) = " + z.angleCosine(w));
        println("    angle(z, w) = " + Complex.angle(z, w));
        println("    z.angle(w) = " + z.angle(w));
        println("    angle(z, z.rotate(90))= " + Complex.angle(z, z.rotate(90)));
        println("    z.angle(z.rotate(90)) = " + z.angle(z.rotate(90)));
        println("    angle(z, z.rotate(-90))= " + Complex.angle(z, z.rotate(-90)));
        println("    z.angle(z.rotate(-90)) = " + z.angle(z.rotate(-90)));
        println("    I**I = " + Complex.I.power(Complex.I));
        println("    TWO**I = " + Complex.TWO.power(Complex.I));
        println("    THREE**I = " + Complex.THREE.power(Complex.I));
        println("    TEN**I = " + Complex.TEN.power(Complex.I));
        println("    I**TWO = " + Complex.I.power(Complex.TWO));
        println("    I**THREE = " + Complex.I.power(Complex.THREE));
        println("    I**TEN = " + Complex.I.power(Complex.TEN));
        Complex u = Complex.I.power(Complex.TEN);
        println("    u = I**TEN = " + u);
        Complex.adjust(u);
        println("    Atfer Complex.adjust(u)");
        println("    u = " + u);
        println("    sqrt(z) = " + Complex.sqrt(z));
        println("    cbrt(z) = " + Complex.cbrt(z));
        println("    square(z) = " + Complex.square(z));
        println("    cube(z) = " + Complex.cube(z));
        println("    Complex.polarForm(1, Math.PI/2) = " + Complex.polarForm(1, Math.PI/2));
        println("    Complex.polarForm(1, Math.PI) = " + Complex.polarForm(1, Math.PI));
    }
}
/*
z = (1.0 + 2.0j)
w = (5.0 + 4.0j)
    z + w = (6.0 + 6.0j)
    z - w = (-4.0 + -2.0j)
    z * w = (-3.0 + 14.0j)
    z / w = (0.3170731707317073 + 0.14634146341463414j)
    z**2 = (-3.0 + 4.0j)
    z**3 = (-11.0 + -2.0j)
    z.inverse() = (0.2 + -0.4j)
    z**-1 = (0.2 + -0.4j)
    z**-2 = (-0.12 + -0.16j)
    z**-3 = (-0.088 + 0.016j)
    -z = (-1.0 + -2.0j)
    conjugate(z) = conjugate((1.0 + 2.0j)) = (1.0 + -2.0j)
    z.conjugate() = ((1.0 + 2.0j)).conjuate() = (1.0 + -2.0j)
    abs(z) = abs((1.0 + 2.0j)) = 2.23606797749979
    norm(z) = norm((1.0 + 2.0j)) = 2.23606797749979
    z.abs() = ((1.0 + 2.0j)).abs() = 2.23606797749979
    z.norm() = ((1.0 + 2.0j)).norm() = 2.23606797749979
    distance(z, w) = distance((1.0 + 2.0j), (5.0 + 4.0j)) = 4.47213595499958
    z.distance(w) = ((1.0 + 2.0j)).distance((5.0 + 4.0j)) = 4.47213595499958
    exp(z) = exp((1.0 + 2.0j)) = (-1.1312043837568138 + 2.471726672004819j)
    log(z) = log((1.0 + 2.0j)) = (0.8047189562170503 + 1.1071487177940904j)
    arg(z) = arg((1.0 + 2.0j)) = 1.1071487177940904
    abs((-1.0 + 2.0j)) = 2.23606797749979
    log((-1.0 + 2.0j)) = (0.8047189562170503 + 2.0344439357957027j)
    abs((-1.0 + -2.0j)) = 2.23606797749979
    log((-1.0 + -2.0j)) = (0.8047189562170503 + -2.0344439357957027j)
    arg((1.0 + -2.0j)) = -1.1071487177940904
    arg((-1.0 + 2.0j)) = 2.0344439357957027
    arg((-1.0 + -2.0j)) = -2.0344439357957027
    sin(z) = sin((1.0 + 2.0j)) = (3.165778513216168 + 1.9596010414216063j)
    cos(z) = cos((1.0 + 2.0j)) = (2.0327230070196656 + -3.0518977991518j)
    tan(z) = tan((1.0 + 2.0j)) = (0.0338128260798966 + 1.0147936161466335j)
    sec(z) = sec((1.0 + 2.0j)) = (0.15117629826557724 + 0.2269736753937216j)
    csc(z) = csc((1.0 + 2.0j)) = (0.22837506559968654 + -0.1413630216124078j)
    cot(z) = cot((1.0 + 2.0j)) = (0.0327977555337525 + -0.9843292264581908j)
    sinh(z) = sinh((1.0 + 2.0j)) = (-0.48905625904129374 + 1.4031192506220407j)
    cosh(z) = cosh((1.0 + 2.0j)) = (-0.6421481247155201 + 1.0686074213827785j)
    tanh(z) = tanh((1.0 + 2.0j)) = (1.16673625724092 + -0.24345820118572523j)
    sech(z) = sech((1.0 + 2.0j)) = (-0.41314934426693994 + -0.6875274386554789j)
    csch(z) = csch((1.0 + 2.0j)) = (-0.2215009308505094 + -0.6354937992538999j)
    coth(z) = coth((1.0 + 2.0j)) = (0.8213297974938518 + 0.17138361290918502j)
    z.rotate(90) = (-2.0 + 1.0000000000000002j)
    z.rotate(-90) = (2.0 + -0.9999999999999999j)
    z == (1.0 + 2.0j) ? true
    z - z = (0.0 + 0.0j)
    (z - z).isZero() ? true
    Complex.ZERO = (0.0 + 0.0j)
    Complex.ONE = (1.0 + 0.0j)
    Complex.TWO = (2.0 + 0.0j)
    Complex.THREE = (3.0 + 0.0j)
    Complex.TEN = (10.0 + 0.0j)
    Complex.I = (0.0 + 1.0j)
    Complex.E = (2.718281828459045 + 0.0j)
    Complex.PI = (3.141592653589793 + 0.0j)
    z = (1.0 + 2.0j)
    w = (5.0 + 4.0j)
    innerProduct(z, w) = (13.0 + -6.0j)
    z.innerProduct(w) = (13.0 + -6.0j)
    isOrthogonal(z, w) = false
    z.isOrthogonal(w) = false
    z.innerProduct(z.rotate(90)) = (4.440892098500626E-16 + 5.0j)
    isOrthogonal(z, z.rotate(90))= true
    z.isOrthogonal(z.rotate(90)) = true
    angleCosine(z, w) = 0.9079593845004517
    z.angleCosine(w) = 0.9079593845004517
    angle(z, w) = 24.77514056883192
    z.angle(w) = 24.77514056883192
    angle(z, z.rotate(90))= 90.0
    z.angle(z.rotate(90)) = 90.0
    angle(z, z.rotate(-90))= 90.0
    z.angle(z.rotate(-90)) = 90.0
    I**I = (0.20787957635076193 + 0.0j)
    TWO**I = (0.7692389013639721 + 0.6389612763136348j)
    THREE**I = (0.4548324228266097 + 0.8905770416677471j)
    TEN**I = (-0.6682015101903132 + 0.7439803369574931j)
    I**TWO = (-1.0 + 1.2246467991473532E-16j)
    I**THREE = (-1.8369701987210297E-16 + -1.0j)
    I**TEN = (-1.0 + 6.123233995736766E-16j)
    u = I**TEN = (-1.0 + 6.123233995736766E-16j)
    Atfer Complex.adjust(u)
    u = (-1.0 + 0.0j)
    sqrt(z) = (1.272019649514069 + 0.7861513777574233j)
    cbrt(z) = (1.2196165079717578 + 0.47171126778938893j)
    square(z) = (-3.0 + 4.0j)
    cube(z) = (-11.0 + -2.0j)
    Complex.polarForm(1, Math.PI/2) = (0.0 + 1.0j)
    Complex.polarForm(1, Math.PI) = (-1.0 + 0.0j)
*/




* 파이썬 언어로 해보는 복소수 계산(파이썬 언어에서 허수 단위는 j로 표기)
>>> z = 1 + 2j
>>> w = 5 + 4j
>>> z + w
(6+6j)
>>> z - w
(-4-2j)
>>> z * w
(-3+14j)
>>> z / w
(0.3170731707317074+0.14634146341463417j)
>>> z**2
(-3+4j)
>>> z**3
(-11-2j)
>>> 1/z
(0.2-0.4j)
>>> z**-1
(0.2-0.4j)
>>> z**-2
(-0.12-0.16j)
>>> z**-3
(-0.08800000000000001+0.016j)
>>> -z
(-1-2j)
>>> z.conjugate()
(1-2j)
>>> abs(z)
2.23606797749979
>>> abs(z - w)
4.47213595499958
>>> import math
>>> def exp(z):
...     return math.e**z
...
>>> exp(z)
(-1.1312043837568135+2.4717266720048188j)
>>> def sin(z):
...     return (math.e**(1j*z) - math.e**(-1j*z))/(2j)
...
>>> sin(z)
(3.165778513216168+1.9596010414216058j)
>>> def cos(z):
...     return (math.e**(1j*z) + math.e**(-1j*z))/2
...
>>> cos(z)
(2.0327230070196656-3.0518977991517997j)
>>> def tan(z):
...     return sin(z)/cos(z)
...
>>> tan(z)
(0.033812826079896816+1.0147936161466338j)
>>> def sec(z):
...     return 1/cos(z)
...
>>> sec(z)
(0.15117629826557727+0.22697367539372162j)
>>> def csc(z):
...     return 1/sin(z)
...
>>> csc(z)
(0.2283750655996866-0.1413630216124078j)
>>> def cot(z):
...     return cos(z)/sin(z)
...
>>> cot(z)
(0.03279775553375272-0.9843292264581911j)
>>> z == 1 + 2j
True
>>> z - z == 0
True
>>> 1j
1j
>>> z.conjugate()*w
(13-6j)



* Python 에서 math 대신 cmath 를 임포트(import, 수입)하여 초월함수 값 계산하기
>>> z = 1 + 2j
>>> w = 5 + 4j
>>> z + w
(6+6j)
>>> z - w
(-4-2j)
>>> z * w
(-3+14j)
>>> z / w
(0.3170731707317074+0.14634146341463417j)
>>> z**2
(-3+4j)
>>> z**3
(-11-2j)
>>> 1/z
(0.2-0.4j)
>>> z**-1
(0.2-0.4j)
>>> z**-2
(-0.12-0.16j)
>>> z**-3
(-0.08800000000000001+0.016j)
>>> -z
(-1-2j)
>>> z.conjugate()
(1-2j)
>>> abs(z)
2.23606797749979
>>> exp(z)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'exp' is not defined
>>> import cmath
>>> cmath.exp(z)
(-1.1312043837568135+2.4717266720048188j)
>>> cmath.sin(z)
(3.165778513216168+1.959601041421606j)
>>> cmath.cos(z)
(2.0327230070196656-3.0518977991518j)
>>> cmath.sec(z)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'sec'
>>> cmath.sinh(z)
(-0.4890562590412937+1.4031192506220407j)
>>> cmath.cosh(z)
(-0.64214812471552+1.0686074213827783j)
>>> cmath.tanh(z)
(1.16673625724092-0.24345820118572525j)
>>> cmath.sech(z)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'sech'
>>> cmath.log(z)
(0.8047189562170503+1.1071487177940904j)




* irb(인터렉티브 ruby)를 실행하여 연습해본 복소수 계산
irb(main):001:0> z = Complex(1, 2)
=> (1+2i)
irb(main):002:0> w = Complex(5,1)
=> (5+1i)
irb(main):003:0> z + w
=> (6+3i)
irb(main):004:0> z - w
=> (-4+1i)
irb(main):005:0> z * w
=> (3+11i)
irb(main):006:0> z / w
=> ((7/26)+(9/26)*i)
irb(main):007:0> z**2
=> (-3+4i)
irb(main):008:0> z**3
=> (-11-2i)
irb(main):009:0> 1/z
=> ((1/5)-(2/5)*i)
irb(main):010:0> z**-1
=> ((1/5)-(2/5)*i)
irb(main):011:0> z**-2
=> ((-3/25)-(4/25)*i)
irb(main):012:0> z**-3
=> ((-11/125)+(2/125)*i)
irb(main):013:0> -z
=> (-1-2i)
irb(main):014:0> z.conjugate
=> (1-2i)
irb(main):015:0> z.abs
=> 2.23606797749979
irb(main):016:0> (z - w).abs
=> 4.12310562561766
irb(main):017:0> require 'complex'
=> true
irb(main):018:0> Math::exp(z)
=> (-1.13120438375681+2.47172667200482i)
irb(main):019:0> Math::sin(z)
=> (3.16577851321617+1.95960104142161i)
irb(main):020:0> Math::cos(z)
=> (2.03272300701967-3.0518977991518i)
irb(main):021:0> Math::tan(z)
=> (0.0338128260798967+1.01479361614663i)
irb(main):022:0> Math::sinh(z)
=> (-0.489056259041294+1.40311925062204i)
irb(main):023:0> Math::cosh(z)
=> (-0.64214812471552+1.06860742138278i)
irb(main):024:0> Math::tanh(z)
=> (1.16673625724092-0.243458201185725i)
irb(main):025:0> Math::log(z)
=> (0.80471895621705+1.10714871779409i)
irb(main):026:0> z - z == 0
=> true
irb(main):027:0> z == Complex(1, 2)
=> true
irb(main):028:0> Math::sqrt(z)
=> (1.27201964951407+0.786151377757423i)
irb(main):029:0> Math::E
=> 2.71828182845905
irb(main):030:0> Math::PI
=> 3.14159265358979
irb(main):031:0> Math::E**z
=> (-1.13120438375681+2.47172667200482i)
irb(main):032:0> Math::exp(z)
=> (-1.13120438375681+2.47172667200482i)



* Lua 언어로 연습해본 복소수 계산
  (참고로 아래의 예제는 http://lua-users.org/wiki/ComplexNumbers 에 있는
             complex 패키지를 이용한 것이다. 이는 Lua 5.1.4 에서도 잘 동작한다. )
--  ------------ Testcode: --------------
-- Filename: TestComplex-01.lua
--           Using the complex class on http://lua-users.org/wiki/ComplexNumbers
--  Execute:  lua TestComplex-01.lua

local complex = require "complex"

function complex.sin( cx )
   local tmp = complex.new(0, 1) * cx;
   return (tmp:exp() - (-tmp):exp())/(complex {0, 2})
end

function complex.cos( cx )
   local tmp = complex.new(0, 1) * cx;
   return (tmp:exp() + (-tmp):exp())/2
end

function complex.tan( cx )
   local tmp = complex.new(0, 2) * cx;
   return (tmp:exp() - 1)/((tmp:exp() + 1)*(complex "i"))
end

function complex.sec( cx )
   local tmp = complex.new(0, 1) * cx;
   return 2/(tmp:exp() + (-tmp):exp())
end

function complex.csc( cx )
   local tmp = complex.new(0, 1) * cx;
   return (complex "2i")/(tmp:exp() - (-tmp):exp())
end

function complex.cot( cx )
   local tmp = complex.new(0, 2) * cx;
   return ((tmp:exp() + 1)*(complex "i"))/(tmp:exp() - 1)
end

function complex.sinh( cx )
   return (cx:exp() - (-cx):exp())/2
end

function complex.cosh( cx )
   return (cx:exp() + (-cx):exp())/2
end

function complex.tanh( cx )
   local tmp = 2 * cx;
   return (tmp:exp() - 1)/(tmp:exp() + 1)
end

function complex.sech( cx )
   return 2/(cx:exp() + (-cx):exp())
end

function complex.csch( cx )
   return 2/(cx:exp() - (-cx):exp())
end

function complex.coth( cx )
   local tmp = 2 * cx;
   return (tmp:exp() + 1)/(tmp:exp() - 1)
end

function complex.cbrt( cx )
   local r, phi = complex.polar( cx )
   local tmp = r^(1/3)
   local tmp2 = phi/3
   return complex.new(tmp*math.cos(tmp2), tmp*math.sin(tmp2))
end

function square( cx )
    return cx*cx
end

function cube( cx )
    return cx*cx*cx
end

-- instantiate of complex
z = complex { 1, 2 }
w = complex.new( 5, 4 )
print( "z = " .. z )
print( "w = " .. w )
print( "    complex.type( z ) = " .. complex.type( z ) )
print( "    complex.type( w ) = " .. complex.type( w ) )
print( "    z - w = " .. z - w )
print( "    z * w = " .. z * w )
print( "    z / w = " .. z / w )
print( "    z^2 = " .. z^2 )
print( "    z^3 = " .. z^3 )
print( "    z^0 = " .. z^0 )
print( "    1/z = " .. 1/z )
print( "    z^-1 = " .. z^-1 )
print( "    z^-2 = " .. z^-2 )
print( "    z^-3 = " .. z^-3 )
print( "    z:conjugate() = " .. z:conjugate() )
print( "    z:abs() = " .. z:abs() )
print( "    |z - w| = " .. (z - w):abs() )
print( "    z:exp() = " .. z:exp() )
print( "    z:ln() = " .. z:ln() )
print( "    complex.sin(z) = " .. complex.sin(z) )
print( "    complex.cos(z) = " .. complex.cos(z) )
print( "    complex.tan(z) = " .. complex.tan(z) )
print( "    complex.sec(z) = " .. complex.sec(z) )
print( "    complex.csc(z) = " .. complex.csc(z) )
print( "    complex.cot(z) = " .. complex.cot(z) )
print( "    complex.sinh(z) = " .. complex.sinh(z) )
print( "    complex.cosh(z) = " .. complex.cosh(z) )
print( "    complex.tanh(z) = " .. complex.tanh(z) )
print( "    complex.sech(z) = " .. complex.sech(z) )
print( "    complex.csch(z) = " .. complex.csch(z) )
print( "    complex.coth(z) = " .. complex.coth(z) )
print( "    z - z == 0 ? ", (z - z == (complex "0")) )
print( "    z == complex \"1+2i\" ? ", z == (complex "1+2i") )
print( "    complex.sqrt(z) = " .. complex.sqrt(z) )
print( "    complex.cbrt(z) = " .. complex.cbrt(z) )
print( "    square(z) = " .. square(z) )
print( "    cube(z) = " .. cube(z) )
print( "    complex.convpolar(1, math.pi/2) = " .. complex.convpolar(1, math.pi/2) )
print( "    complex.convpolar(1, math.pi) = " .. complex.convpolar(1, math.pi) )
print( "    complex.convpolar(1, math.pi/2):round(15) = " .. complex.convpolar(1, math.pi/2):round(15) )
print( "    complex.convpolardeg(1, math.pi):round(15) = " .. complex.convpolar(1, math.pi):round(15) )
print( "    complex.convpolardeg(1, 90) = " .. complex.convpolardeg(1, 90) )
print( "    complex.convpolardeg(1, 180) = " .. complex.convpolardeg(1, 180) )
print( "    complex.convpolardeg(1, 90):round(15) = " .. complex.convpolardeg(1, 90):round(15) )
print( "    complex.convpolardeg(1, 180):round(15) = " .. complex.convpolardeg(1, 180):round(15) )
print( "    complex.tostring( z, \"%.2f\" ) = " .. complex.tostring( z, "%.2f" ) )
local r, phi = complex.polar( {0,3} )
print( "    complex.polar( {3,0} ) = " .. r .. ",  " .. phi )
r, phi = complex.polar( z )
print( "    complex.polar( z ) = " .. r .. ",  " .. phi )
r, phi = complex.polardeg( z )
print( "    complex.polardeg( z ) = " .. r .. ",  " .. phi )
local re, im = complex.get( z )
print( "    complex.get( z ) = " .. re .. ",  " .. im .. "        // the real and imaginary parts of z" )
re, im = complex.get( w )
print( "    complex.get( w ) = " .. re .. ",  " .. im .. "        // the real and imaginary parts of z" )
print( "    complex.mulconjugate( z ) = " .. complex.mulconjugate( z ) .. "   // the square of abs(z)" )
print( "    complex.mulconjugate( w ) = " .. complex.mulconjugate( w ) .. "  // the square of abs(w)" )
--[[
Execution Result:
z = 1+2i
w = 5+4i
    complex.type( z ) = complex
    complex.type( w ) = complex
    z - w = -4-2i
    z * w = -3+14i
    z / w = 0.31707317073171+0.14634146341463i
    z^2 = -3+4i
    z^3 = -11-2i
    z^0 = 1+2i
    1/z = 0.2-0.4i
    z^-1 = 0.2-0.4i
    z^-2 = -0.12-0.16i
    z^-3 = -0.088+0.016i
    z:conjugate() = 1-2i
    z:abs() = 2.2360679774998
    |z - w| = 4.4721359549996
    z:exp() = -1.1312043837568+2.4717266720048i
    z:ln() = 0.80471895621705+1.1071487177941i
    complex.sin(z) = 3.1657785132162+1.9596010414216i
    complex.cos(z) = 2.0327230070197-3.0518977991518i
    complex.tan(z) = 0.033812826079897+1.0147936161466i
    complex.sec(z) = 0.15117629826558+0.22697367539372i
    complex.csc(z) = 0.22837506559969-0.14136302161241i
    complex.cot(z) = 0.032797755533753-0.98432922645819i
    complex.sinh(z) = -0.48905625904129+1.403119250622i
    complex.cosh(z) = -0.64214812471552+1.0686074213828i
    complex.tanh(z) = 1.1667362572409-0.24345820118573i
    complex.sech(z) = -0.41314934426694-0.68752743865548i
    complex.csch(z) = -0.22150093085051-0.6354937992539i
    complex.coth(z) = 0.82132979749385+0.17138361290918i
    z - z == 0 ?        true
    z == complex "1+2i" ?       true
    complex.sqrt(z) = 1.2720196495141+0.78615137775742i
    complex.cbrt(z) = 1.2196165079718+0.47171126778939i
    square(z) = -3+4i
    cube(z) = -11-2i
    complex.convpolar(1, math.pi/2) = 6.1232339957368e-017+i
    complex.convpolar(1, math.pi) = -1+1.2246467991474e-016i
    complex.convpolar(1, math.pi/2):round(15) = i
    complex.convpolardeg(1, math.pi):round(15) = -1
    complex.convpolardeg(1, 90) = 6.1232339957368e-017+i
    complex.convpolardeg(1, 180) = -1+1.2246467991474e-016i
    complex.convpolardeg(1, 90):round(15) = i
    complex.convpolardeg(1, 180):round(15) = -1
    complex.tostring( z, "%.2f" ) = 1.00+2.00i
    complex.polar( {3,0} ) = 3,  1.5707963267949
    complex.polar( z ) = 2.2360679774998,  1.1071487177941
    complex.polardeg( z ) = 2.2360679774998,  63.434948822922
    complex.get( z ) = 1,  2       // the real and imaginary parts of z
    complex.get( w ) = 5,  4       // the real and imaginary parts of z
    complex.mulconjugate( z ) = 5  // the square of abs(z)
    complex.mulconjugate( w ) = 41  // the square of abs(w)
--]]


Posted by Scripter
,

GiNaC 홈페이지 : http://www.ginac.de


GiNaC is an open framework for symbolic computation within the C++ programming language
 


* Ubuntu 에서 GiNaC 설치하기
"시냅틱 패키지 관리자" 사용 또는
$ sudo apt-get install ginac


* Mac 에서 GiNaC 설치하기
$ sudo port install ginac


* 예제 소스(파일명: seventh.cpp) - 오일러의 수 계산하는 예제
#include <ginac/ginac.h>
using namespace GiNaC;
     
ex EulerNumber(unsigned n)
{
    symbol x;
    const ex generator = pow(cosh(x),-1);
    return generator.diff(x,n).subs(x==0);
}
     
int main()
{
    for (unsigned i=0; i<11; i+=2)
        std::cout << EulerNumber(i) << std::endl;
    return 0;
}


$ export CPPFLAGS="-I/opt/local/include"      
$ export LIBPATH="-L/opt/local/lib -lginac"   
$ g++ -o seventh seventh.cpp -lginac $CPPFLAGS $LIBPATH                    
$ ./seventh                                   
1
-1
5
-61
1385
-50521


Posted by Scripter
,
KAlgebra 는 Ubuntu 10.4.x (루시드 링스) 에 기본으로 설치되어 있는 간이 계산기로서 2D, 3D 그래프도 그려준다. KAlgebra 를 실행하려면 Ubuntu 의 주메뉴에서 "프로그램" -> "교육" -> "KAlgebra" 를 차례로 선택히면 된다. KAlgebra 실행 창의 메뉴에서 "Help"  > "KAlgebra Handbook" 하여 Hep 창이 뜨지 않으면 "시냅틱 패키지 관리자"를 실행하여 khelpcenter 를 설치한다. (아래와 같은 Help 창이 뜬다.)


* KAlgebra 의 Help 화면



* KAlgebra 를 실행하여 간단한 수식 계산하기





* KAlgebra 가 그려준 함수 y = x^2 - 2x  의 그래프




* 의의 그림울 저장하기 직전의 KAlgebra 창 스샷




Posted by Scripter
,
For a given square matrix A, if there exist two matrices Q and R such that

                                         A = QR

where Q is an orthogonal matrix (i.e transpose(Q)=inverse(Q)) and R is an upper traingular matrix. then the product QR is called a QR decomposition or QR fatorization of A


* Mathematica 에서 QR 분해하기 (분수로 계산)




* Mathematica 에서 QR 분해하기 (부동소수점수 계산)





* 64bit Ubuntu 의 Octave 에서 QR 분해하기
octave:1> a = [3, 4; 1, 2];
octave:2> [q, r] = qr(a)
q =

   0.94868  -0.31623
   0.31623   0.94868

r =

   3.16228   4.42719
   0.00000   0.63246

octave:3> q*r
ans =

   3.0000   4.0000
   1.0000   2.0000

octave:4> [q, r, p] = qr(a)
q =

   0.89443   0.44721
   0.44721  -0.89443

r =

   4.47214   3.13050
   0.00000   0.44721

p =

   0   1
   1   0

octave:5> q*r
ans =

   4   3
   2   1

octave:6> a
a =

   3   4
   1   2

octave:7> q*r*p - a
ans =

   0   0
   0   0





* 다음은 Octave 실행 창에서 help 명령으로 qr 사용법을 알아본 것이다.
octave:1> help qr
adable Function: [Q, R, P] = qr (A)
     Compute the QR factorization of A, using standard LAPACK
     subroutines.  For example, given the matrix `a = [1, 2; 3, 4]',

          [q, r] = qr (a)

     returns

          q =

            -0.31623  -0.94868
            -0.94868   0.31623

          r =

            -3.16228  -4.42719
             0.00000  -0.63246

     The `qr' factorization has applications in the solution of least
     squares problems

          `min norm(A x - b)'

     for overdetermined systems of equations (i.e., `a'  is a tall,
     thin matrix).  The QR factorization is `q * r = a' where `q' is an
     orthogonal matrix and `r' is upper triangular.

     The permuted QR factorization `[Q, R, P] = qr (A)' forms the QR
     factorization such that the diagonal entries of `r' are decreasing
     in magnitude order.  For example, given the matrix `a = [1, 2; 3,
     4]',

          [q, r, p] = qr(a)

     returns

          q =

            -0.44721  -0.89443
            -0.89443   0.44721

          r =

            -4.47214  -3.13050
             0.00000   0.44721

          p =

             0  1
             1  0

     The permuted `qr' factorization `[q, r, p] = qr (a)' factorization
     allows the construction of an orthogonal basis of `span (a)'.

Overloaded function:

   spqr (sparse matrix, ...)

   spqr (sparse complex matrix, ...)

   spqr (sparse bool matrix, ...)

qr is a built-in function

Additional help for built-in functions and operators is
available in the on-line version of the manual.  Use the command
`doc <topic>' to search the manual index.

Help and information about Octave is also available on the WWW
at http://www.octave.org and via the help@octave.org
mailing list.








* 64bit Ubuntu 의 Python 2.6.5 에서 QR 분해하기 (아래의 진한 글자만 입력)


Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from numpy import *
>>> import scipy as Sci
>>> import scipy.linalg
>>> a = mat("3, 4; 1, 2")
>>> q, r = scipy.linalg.qr(a)
>>> q2, r2 = matrix(q), matrix(r)
>>> q2*r2
matrix([[ 3.,  4.],
        [ 1.,  2.]])
>>> q2*r2 - a
matrix([[  0.00000000e+00,   0.00000000e+00],
        [ -1.11022302e-16,  -8.88178420e-16]])
>>> q2*r2 == a
matrix([[ True,  True],
        [False, False]], dtype=bool)

* Ububtu 에서 Python 인터프리터로 자업 중인 창을 쓰한 것




* Ubuntu 에서 Python 인터프리터로 자업 중인 화면 스샷





* Maxima 는 (아쉽지만) 아직 QR 분해를 지원하지 않는다.


* Ubuntu 에서 SciLab 을 이용하여 QR 분해하기
  (참고: SciLab 은 Ubuntu 를 설치하면 "프로그램"->"과학" 메뉴에 있는 기본 앱이다.)

a = [3, 1, 4, 2]
A = matrix(a, 2, 2)
[Q, R] = qr(A)
[Q Q'*A R]




* gsl 을 이용하여 QR 분해하는 C 소스 코드

/***********************************************
  Filename: example-05.c
  Purpose:
              Test GSL library.
              http://www.gnu.org/software/gsl/
  On Window XP & cygwin:
  On Ubuntu
        Compile: gcc -Wall -I/usr/local/include -c example-05.c
               Link: gcc -o example-05 -L/usr/local/lib example-05.o -lgsl -lgslcblas -lm

 On Mac OS X Lion:
        Compile: gcc -Wall -I/usr/local/include -c example-05.c
               Link: gcc -o example-05 -L/usr/local/lib example-05.o -lgsl -lgslcblas -lm

  Execute: ./example-05

  Result:
A is a 2 by 2 matrix
A =
[ [   3.00000000  4.00000000 ],
  [   1.00000000  2.00000000 ] ]
A =
[ [  -3.16227766 -4.42718872 ],
  [   0.16227766  0.63245553 ] ]
tau = [   1.94868330  0.00000000 ]
R =
[ [  -3.16227766 -4.42718872 ],
  [   0.00000000  0.63245553 ] ]
Q =
[ [   0.00000000  0.00000000 ],
  [   0.16227766  0.00000000 ] ]
***************************************************/

#include <stdio.h>
#include <string.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>

void printVector(char *msg, gsl_vector *x, const char *fmt) {
   if (msg != NULL && strlen(msg) > 0)
       printf("%s", msg);
    size_t n = x->size;
    size_t i;
    printf("[ ");
    printf (fmt, gsl_vector_get(x, 0));
    for (i = 1; i < n; i++) {
        printf (fmt, gsl_vector_get(x, i));
    }
    printf(" ]\n");
}

void printMatrix(char *msg, gsl_matrix *a, char *fmt) {
    if (msg != NULL && strlen(msg) > 0)
        printf("%s\n", msg);
    size_t m = a->size1, n = a->size2;
    size_t i, j;
    printf("[ [ ");
    printf (fmt, gsl_matrix_get(a, 0, 0));
    for (j = 1; j < n; j++) {
        printf (fmt, gsl_matrix_get(a, 0, j));
    }
    printf(" ]");
    if (m > 1)
        printf(",\n");
    for (i = 1; i < m; i++) {
        printf("  [ ");
        printf (fmt, gsl_matrix_get(a, i, 0));
        for (j = 1; j < n; j++) {
            printf (fmt, gsl_matrix_get(a, i, j));
    }
    printf(" ]");
    if (i < m -1)
        printf(",\n");
    }
    printf(" ]\n");
}

void product(gsl_matrix *c, const gsl_matrix *a, const gsl_matrix *b) {
    size_t m = a->size1, n = a->size2, p = b->size2;
    size_t i, j, k;
    double sum;
    for (i = 0; i < m; i++) {
        for (k = 0; k < p; k++) {
            sum = 0.0;
            for (j = 0; j < n; j++) {
                sum = sum + gsl_matrix_get(a, i, j)*gsl_matrix_get(b, j, k);
            }
            gsl_matrix_set (c, i, k, sum);
        }
    }
}

void productWIthRightVector(gsl_vector *c, const gsl_matrix *a, const gsl_vector *b) {
    size_t m = a->size1, n = b->size;
    size_t i, j;
    double sum;
    for (i = 0; i < m; i++) {
        sum = 0.0;
        for (j = 0; j < n; j++) {
            sum = sum + gsl_matrix_get(a, i, j)*gsl_vector_get(b, j);
        }
        gsl_vector_set(c, i, sum);
    }
}

void productWIthLeftVector(gsl_vector *c, const gsl_vector *a, const gsl_matrix *b) {
    size_t m = a->size, n = b->size2;
    size_t i, j;
    double sum;
    for (j = 0; j < n; j++) {
        sum = 0.0;
        for (i = 0; i < m; i++) {
            sum = sum + gsl_vector_get(a, j)*gsl_matrix_get(b, i, j);
        }
        gsl_vector_set(c, j, sum);
    }
}

void add(gsl_matrix *c, const gsl_matrix *a, const gsl_matrix *b) {
    size_t m = a->size1, n = a->size2;
    size_t i, j;
    double v;
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            v = gsl_matrix_get (a, i, j) + gsl_matrix_get (b, i, j);
         gsl_matrix_set (c, i, j, v);
  }
 }
}

void subtract(gsl_matrix *c, const gsl_matrix *a, const gsl_matrix *b) {
    size_t m = a->size1, n = a->size2;
    size_t i, j;
    double v;
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            v = gsl_matrix_get (a, i, j) - gsl_matrix_get (b, i, j);
            gsl_matrix_set (c, i, j, v);
        }
    }
}

void multiply(gsl_matrix *c, double x, const gsl_matrix *a) {
    size_t m = a->size1, n = a->size2;
    size_t i, j;
    double v;
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            v = x*gsl_matrix_get (a, i, j);
         gsl_matrix_set (c, i, j, v);
  }
 }
}

void set(gsl_matrix *c, const gsl_matrix *a) {
    gsl_matrix_memcpy(c, a);
}

double trace(const gsl_matrix *a) {
 size_t m = a->size1;
 size_t i;
 double sum = 0;
    for (i = 0; i < m; i++) {
        sum = sum + gsl_matrix_get (a, i, i);
 }
 return sum;
}

void transpose(gsl_matrix *c, const gsl_matrix *a) {
    size_t m = a->size1, n = a->size2;
    size_t i, j;
    for (i = 0; i < n; i++) {
        for (j = 0; j < m; j++) {
         gsl_matrix_set (c, i, j, gsl_matrix_get (a, j, i));
  }
 }
}

void getQR(gsl_matrix *Q, gsl_matrix *R, const gsl_matrix *A, const gsl_vector *tau) {
   size_t m = A->size1;
   size_t n = A->size2;
   size_t i, j;
   for (i =0 ; i < m; i++) {
       for (j =0 ; j < n; j++) {
           if (i > j) {
               gsl_matrix_set(R, i, j, 0);
               gsl_matrix_set(Q, i, j, gsl_matrix_get(A, i, j));
           }
           else {
               gsl_matrix_set(R, i, j, gsl_matrix_get(A, i, j));
               gsl_matrix_set(Q, i, j, 0);
           }
       }
   }
}

int main(void)  {
    size_t n = 2;
    gsl_vector *tau = gsl_vector_alloc(n);
    // size_t i, j;
    gsl_matrix *A = gsl_matrix_alloc(n, n);
    gsl_matrix *Q = gsl_matrix_alloc(n, n);
    gsl_matrix *R = gsl_matrix_alloc(n, n);

    gsl_matrix_set (A, 0, 0, 3);
    gsl_matrix_set (A, 0, 1, 4);
    gsl_matrix_set (A, 1, 0, 1);
    gsl_matrix_set (A, 1, 1, 2);

    printf ("A is a 2 by 2 matrix\n");
    printMatrix("A = ", A, "%12.8f");

    gsl_linalg_QR_decomp(A, tau);

    printMatrix("A = ", A, "%12.8f");
    printVector("tau = ", tau, "%12.8f");

    getQR(Q, R, A, tau);
    printMatrix("R = ", R, "%12.8f");
    printMatrix("Q = ", Q, "%12.8f");

     gsl_matrix_free (Q);
     gsl_matrix_free (R);
     gsl_matrix_free (A);
     gsl_vector_free (tau);
     return 0;
}




 

Posted by Scripter
,

ALGLIB is a cross-platform open source numerical analysis and data processing library. It is written in specially designed pseudocode which is automatically translated into several target programming languages (C++, C# and other). ALGLIB is relatively young project - active development started only in 2008, while GSL, for example, has 14 years long history. However, it is actively developed with new releases every 1–2 months.

참조: http://en.wikipedia.org/wiki/ALGLIB
ALGLIB 홈페이지: http://www.alglib.net/
ALGLIB 다운로드: http://www.alglib.net/download.php


 * ALGLIB 를 이용하여 LU 분해하는 파이썬 언어 소스

#!/usr/bin/env python

"""
 Filename: testLU2.py

    Find a LU decomposition of a given square matrix by using
    the function 'xalglib.rmatrixlu' of the library ALGLIB
    (www.alglib.net), Sergey Bochkanov and Vladimir Bystritsky.

    And find also the inverse of a given invertible square matrix
    by using the function 'xalglib.rmatrixinverse' of the library ALGLIN.

 Liscense: GPLv2
 Author: Copyright (c) 2011/09/19 (Mon)  PKim  pkim01 (AT) paran (DOT) com
"""


import math
import xalglib

class RVector:
    def __init__(self, arr):
        a = []
        for i in range(len(arr)):
            a.append(arr[i])
        self.arr = a
    def __str__(self):
        return str(self.arr)
    def __getitem__(self, key):
        return self.arr[key]
    def __setitem__(self, key, value):
        self.arr[i] = value
    def __add__(self, other):
        m = self.size()
        a = []
        for i in range(m):
           a.append(self[i] + other[i])
        return RVector(a)
    def __neg__(self):
        m = self.size()
        a = []
        for i in range(m):
           a.append(-self[i])
        return RVector(a)
    def __sub__(self, other):
        m = self.size()
        a = []
        for i in range(m):
           a.append(self[i] - other[i])
        return RVector(a)
    def __rmul__(self, other):
        if type(other) == int or type(other) == long or type(other) == float:
            m = self.size()
            a = []
            for i in range(m):
               a.append(other*self[i])
            return RVector(a)
        else:
            return None
    def angle(self, other):
        return math.acos( self.dot(other) / (self.dot(self) * other.dot(other)) )
    def cross(self, other):
        a = []
        value = self[1]*other[2] - self[2]*other[1]
        a.append(value)
        value = self[2]*other[0] - self[0]*other[2]
        a.append(value)
        value = self[0]*other[1] - self[1]*other[0]
        a.append(value)
        return RVector(a)
    def norm(self):
        n = self.size()
        sum = 0
        for i in range(n):
            sum = sum + self[i]*self[i]
        return math.sqrt(sum)
    def dot(self, other):
        n = self.size()
        sum = 0
        for i in range(n):
            sum = sum + self[i]*other[i]
        return sum
    def size(self):
        return len(self.arr)
    def printVector(self, msg):
        if msg != None and len(msg) > 0:
            print msg,
        print self


Posted by Scripter
,
여기서는 2x2 정방행렬

        A = [4, 3; 6, 3]

의 LU 분해(LU decomposition)를 위해 여러 가지 도구

        Mathematica, Maxima, Octave, Scipy, 
        Jama 패키지를 이용한 Java 애플리케이션,
        Jama 패키지를 이용한 Groovy 애플리케이션

로는 각각 어떻게 해결하는지 알아보고자 한다.
,


* Mathematica 를 이용하여 행렬 계산하기
  (참고: Mathematica 에서는 LUDecompostion 이라는 함수가 준비되어 있다.)




* Maxima 를 이용하여 행렬 계산하기 (행렬 곱셈, 전치행렬, 행렬식, 역행렬 등)
  (참고: Maxima 애서는 변수에 수식 계산에 의한 값을 할당할 때 쓰는 할당 연샂자가 등호(=)가
           아니라 콜론(:)임에 유의한다.   Maxima 에서는 LU 분해를 위해 lu_factor 함수와 
           get_lufactors 함수를 연이어 사용한다,)





* Octave 를 이용하여 정방행렬을  LU 분해하기
** Octave 소스
   (참고: 함수 lu 를 호출하면 하삼각행렬 l, 상삼각행렬 u, 열교환 행혈 p 를 한꺼번에
            구할 수 있다.)
a = [4, 3; 6, 3]
[l, u, p] = lu(a)
p*l*u
p*l*u == a


** Octave 명령 창에서 행렬 A 의 LU 분해를 구하고 검증하기





* Python 2.7 & Numpy & Scipy를 이용하여 LU 분해 구하기
  (참고: 함수 lu_factor 를 불러 써야 하는데 이 함수는 입력 데이터와 출력 데이터를 모두
            array 타입으로 하므로, matrix 타입과 array 터입을 상호 변환하는 과정이 팔요하다.
                     matrixType = matrix(arrayType)
                     arrayType = array(matrixType)
  )

** 파이썬 소스
#!/usr/bin/env python
"""
Find a LU decomposition of a given square matrix.
Use the function 'lu_factor' of the module 'scipy.linalg.decomp_lu'.
Copyright  (c) 2011/09/18  (Sun)    PKim     pkim01 (AT) paran (DOT) com
"""
import numpy as np
import scipy as sp
from scipy import linalg
from numpy import *
from scipy.linalg.decomp_lu import *

def printWithType (x):
    print x, "   as", type(x)
   
def getLU(lu, piv):
    """
        Input
                lu      LU array
                piv    pivot array
        Output
                l       array for the lower diagonal matrix
                u      array for the upper diagonal matrix
                p      array for the permutation
    """
    l = lu.copy()
    u = lu.copy()
    for i in range(len(lu)):
        for j in range(len(lu[0])):
          if i == j:
              l[i][j] = 1
          elif i > j:
             u[i][j] = 0
          else:
             l[i][j] = 0
    p = np.eye(len(lu))
    for i in range(len(piv)):
        if i != piv[i]:
            tmp = p[piv[i]].copy()
            p[piv[i]] =  p[i].copy()
            p[i] = tmp
    return l, u, p

a = array([[4, 3], [6, 3]])
# a = array([[1, 2, 5], [2, 1, 2], [7, 1, 1]])   # This shoud work, too!
A = matrix(a)
print "A ="
printWithType(A)
print "a ="
printWithType(a)

lu, piv =lu_factor(a, False)
print "lu ="
printWithType(lu)
print "piv ="
printWithType(piv)

l, u, p = getLU(lu, piv)
print "l ="
printWithType(l)
print "u ="
printWithType(u)
print "p ="
printWithType(p)

L = matrix(l)
U = matrix(u)
P = matrix(p)

print "L ="
printWithType(L)
print "U ="
printWithType(U)
print "P ="
printWithType(P)
print "P*A =", P*A
print "L*U =", L*U
print P*A == L*U


** 위의 소스를 실행한 결과
A =
[[4 3]
 [6 3]]     as <class 'numpy.matrixlib.defmatrix.matrix'>
a =
[[4 3]
 [6 3]]     as <type 'numpy.ndarray'>
lu =
[[ 6.          3.        ]
 [ 0.66666667  1.        ]]     as <type 'numpy.ndarray'>
piv =
[1 1]     as <type 'numpy.ndarray'>
l =
[[ 1.          0.        ]
 [ 0.66666667  1.        ]]     as <type 'numpy.ndarray'>
u =
[[ 6.  3.]
 [ 0.  1.]]     as <type 'numpy.ndarray'>
p =
[[ 0.  1.]
 [ 1.  0.]]     as <type 'numpy.ndarray'>
L =
[[ 1.          0.        ]
 [ 0.66666667  1.        ]]     as <class 'numpy.matrixlib.defmatrix.matrix'>
U =
[[ 6.  3.]
 [ 0.  1.]]     as <class 'numpy.matrixlib.defmatrix.matrix'>
P =
[[ 0.  1.]
 [ 1.  0.]]     as <class 'numpy.matrixlib.defmatrix.matrix'>
P*A = [[ 6.  3.]
 [ 4.  3.]]
L*U = [[ 6.  3.]
 [ 4.  3.]]
[[ True  True]
 [ True  True]]


* Jama 패키지를 이용한 Java 애플리케이션
  (참고: JAMA is a basic linear algebra package for Java. )

** Java 소스
/**
 * Filename: TestLuDecompose.java
 *
 *  Putpose
 *            Test the LU decomposition of the Jama 1.0.2 package,
 *                 which is a famous Java Matrix package downloadable
 *                 at t http://math.nist.gov/javanumerics/jama/
 *
 *  Compile: javac -cp .;Jama-1.0.2.jar -d . TestLuDecompose.java
 *  Execute: java -classpath .;Jama-1.0.2.jar scripting.tistory.examples.Jama.TestLuDecompose
 *
 *  Author:  2011/09/19 (Mon)  Copyright (C)   pkim01 (AT) paran (DOT) com
 */

package scripting.tistory.examples.Jama;

import Jama.*;
import java.util.Date;

/*---   Example testing the LU decomposition of the JAMA package.  ---*/

public class TestLuDecompose {

   private static void print (String s) {
      System.out.print(s);
   }

   private static void printMatrix(String msg, Matrix A) {
       if (msg != null && msg.length() > 0)
           print(msg + "\n");
       int m = A.getRowDimension();
       int n = A.getColumnDimension();
       for (int i =0 ; i < m; i++) {
           for (int j =0 ; j < n; j++) {
               print(fixedWidthDoubletoString(A.get(i, j), 12, 3));
           }
           print("\n");
       }
   }

   private static void printPivot(String msg, int[] pvt) {
       if (msg != null && msg.length() > 0)
           print(msg + "[ ");
       int k = pvt.length;
       if (k > 0)
            print("" + pvt[0]);
       for (int i =1 ; i < k; i++) {
            print(", " + pvt[i]);
       }
       print(" ]\n");
   }

   private static Matrix applyPivot(Matrix A, int[] pvt) {
       int k = pvt.length;
       int m = A.getRowDimension();
       int n = A.getColumnDimension();
       double[][] t = new double[m][n];
       for (int i =0 ; i < m; i++) {
           for (int j =0 ; j < n; j++) {
              t[pvt[i]][j] = A.get(i, j);
           }
       }
        return new Matrix(t);
   }

   /** Format double with Fw.d. **/
   public static String fixedWidthDoubletoString (double x, int w, int d) {
      java.text.DecimalFormat fmt = new java.text.DecimalFormat();
      fmt.setMaximumFractionDigits(d);
      fmt.setMinimumFractionDigits(d);
      fmt.setGroupingUsed(false);
      String s = fmt.format(x);
      while (s.length() < w) {
         s = " " + s;
      }
      return s;
   }

   /** Format integer with Iw. **/
   public static String fixedWidthIntegertoString (int n, int w) {
      String s = Integer.toString(n);
      while (s.length() < w) {
         s = " " + s;
      }
      return s;
   }

   public static void main (String argv[]) {
      double eps = Math.pow(2.0,-52.0);
      int n = 2;
      double[][] a = new double[n][n];
      a[0][0] = 4;
      a[0][1] = 3;
      a[1][0] = 6;
      a[1][1] = 3;

      Matrix A = new Matrix (a);
      printMatrix("A = ", A);

      LUDecomposition LU = new LUDecomposition(A);
      Matrix L = LU.getL();
      Matrix U = LU.getU();
      int[] p = LU.getPivot();

      printMatrix("L = ", L);
      printMatrix("U = ", U);
      printPivot("pivot = ", p);
      printMatrix("L*U = ", L.times(U));

      // This should eqal to A.
      printMatrix("applyPuvot(L*U) = ", applyPivot(L.times(U), p));

      // This should eqal to A., too.
      printMatrix("t(L*U).getMatrix(p,0,n-1) = ", (L.times(U)).getMatrix(p,0,n-1));
      Matrix R = L.times(U).minus(A.getMatrix(p,0,n-1));
      printMatrix("R = ", R);

      double res = R.norm1()/(n*eps);
      print("The error is about ");
      print(fixedWidthDoubletoString(res,12, 3));
      print(".\n");
   }
}

/***********************************
  Result output:
 A =
        4.000       3.000
        6.000       3.000
 L =
        1.000       0.000
        0.667       1.000
 U =
        6.000       3.000
        0.000       1.000
 pivot = [ 1, 0 ]
 L*U =
        6.000       3.000
        4.000       3.000
 applyPuvot(L*U) =
        4.000       3.000
        6.000       3.000
 t(L*U).getMatrix(p,0,n-1) =
        4.000       3.000
        6.000       3.000
 R =
        0.000       0.000
        0.000       0.000
 The error is about        0.000.
***************************************/


* Jama 패키지를 이용한 Groovy 애플리케이션
  (참고: Groovy 언어는 Java오언어와 달리 퍼레이터 오바로딩을 지원하므로 ,
           두 행렬의 합과 곱, 또 정방행렬의 멱승을 구현하고 테스트하는 루틴을
            추가하였다. 행렬을 출력하는 printMatrix 함수도 개선하였다.)
**  Groovy 소스
/**
 * Filename: testLuDecompose.groovy
 *
 *  Putpose
 *            Test the LU decomposition of the Jama 1.0.2 package,
 *                 which is a famous Java Matrix package downloadable
 *                 at t http://math.nist.gov/javanumerics/jama/
 *
 *  Execute: groovy testLuDecompose.groovy
 *
 *  Author:  2011/09/19 (Mon)  Copyright (C)   pkim01 (AT) paran (DOT) com
 */

package scripting.tistory.examples.Jama;

import Jama.*;
import java.util.Date;

/*---   Example testing the LU decomposition of the JAMA package.  ---*/

public class MyMatrix extends Matrix {

      public MyMatrix(double[][] a) {
          super(a);
      }

      public MyMatrix(Matrix M) {
          this(M.getArray());
      }

      public Matrix multiply(Matrix B) {
          return (this as Matrix).times(B);
      }

      public Matrix multiply(double c) {
          return (this as Matrix).times(c);
      }

      public MyMatrix power(int k) {
          Matrix M = super.copy();
          if (k == 0) {
         int m = super.getRowDimension();
          int n = super.getColumnDimension();
              return new MyMatrix(Matrix.identity(m, n));
          }
          else if (k == -1) {
              if (M.det() != 0.0) {
                  return new MyMatrix(M.inverse());
              }
              return null;
          }
          else if (k < -1) {
              if (M.det() != 0.0) {
                  Matrix N =  M.inverse();
                  Matrix K =  N.copy();
              for (int i = 1 ; i < -k; i++) {
                   K = K.times(N);
               }
                  return new MyMatrix(K);
              }
              return null;
          }
          else {
       for (int i = 1 ; i < k; i++) {
               M = M.times(this);
           }
              return new MyMatrix(M);
          }
      }
}


def printMatrix(String msg, Matrix A, width=12, dwidth=3) {
   if (msg != null && msg.length() > 0)
       print(msg + "\n");
   int m = A.getRowDimension();
   int n = A.getColumnDimension();
   for (int i =0 ; i < m; i++) {
       for (int j =0 ; j < n; j++) {
           print(fixedWidthDoubletoString(A.get(i, j), width, dwidth));
       }
       print("\n");
   }
}

def printPivot(String msg, int[] pvt) {
   if (msg != null && msg.length() > 0)
       print(msg + "[ ");
   int k = pvt.length;
   if (k > 0)
    print("" + pvt[0]);
   for (int i =1 ; i < k; i++) {
    print(", " + pvt[i]);
   }
     print(" ]\n");
}

def applyPivot(Matrix A, int[] pvt) {
   int k = pvt.length;
   int m = A.getRowDimension();
   int n = A.getColumnDimension();
   double[][] t = new double[m][n];
   for (int i =0 ; i < m; i++) {
       for (int j =0 ; j < n; j++) {
           t[pvt[i]][j] = A.get(i, j);
        }
   }
   return new Matrix(t);
}

/** Format double with Fw.d. **/
def fixedWidthDoubletoString (double x, int w, int d) {
      java.text.DecimalFormat fmt = new java.text.DecimalFormat();
      fmt.setMaximumFractionDigits(d);
      fmt.setMinimumFractionDigits(d);
      fmt.setGroupingUsed(false);
      String s = fmt.format(x);
      while (s.length() < w) {
         s = " " + s;
      }
      return s;
}

/** Format integer with Iw. **/
def fixedWidthIntegertoString (int n, int w) {
      String s = Integer.toString(n);
      while (s.length() < w) {
         s = " " + s;
      }
      return s;
}


double eps = Math.pow(2.0,-52.0);
int n = 2;
double[][] a = new double[n][n];
a[0][0] = 4;
a[0][1] = 3;
a[1][0] = 6;
a[1][1] = 3;

MyMatrix A = a as MyMatrix;
printMatrix("A = ", A);

LUDecomposition LU = new LUDecomposition(A);
Matrix L = LU.getL();
Matrix U = LU.getU();
int[] p = LU.getPivot();

printMatrix("L = ", L);
printMatrix("U = ", U);
printPivot("pivot = ", p);
printMatrix("L*U = ", L.times(U));

// This should eqal to A.
printMatrix("applyPuvot(L*U) = ", applyPivot(L.times(U), p));

// This should eqal to A., too.
Matrix R = L.times(U).minus(A.getMatrix(p,0,n-1));
printMatrix("R = ", R);

double res = R.norm1()/(n*eps);
print("The error is about ");
print(fixedWidthDoubletoString(res,12, 3));
print(".\n");

printMatrix("A + A = ", A + A);
printMatrix("A*A = ", A*A);
printMatrix("A.inverse() = ", A.inverse());
printMatrix("A*A.inverse() = ", A*A.inverse());
print("A.det() = " + A.det() + "\n");
printMatrix("A*3 = ", A*3);
printMatrix("A = ", A);
printMatrix("A**2 = ", A**2);
printMatrix("A**2 = ", A**2);
printMatrix("A**0 = ", A**0);
printMatrix("A**3 = ", A**3);
printMatrix("A**4 = ", A**4);
printMatrix("A**5 = ", A**5);
printMatrix("A**6 = ", A**6);
printMatrix("A**7 = ", A**7);
printMatrix("A**8 = ", A**8, 15, 3);
printMatrix("A**9 = ", A**9, 15, 3);
printMatrix("A**10 = ", A**10, 15, 3);
printMatrix("A**(-1) = ", A**(-1));
printMatrix("A**(-2) = ", A**(-2));
printMatrix("A**(-2)*A**2 = ", A**(-2)*A**2);

/*------------------------------------
  Execution Result:
A =
       4.000       3.000
       6.000       3.000
L =
       1.000       0.000
       0.667       1.000
U =
       6.000       3.000
       0.000       1.000
pivot = [ 1, 0 ]
L*U =
       6.000       3.000
       4.000       3.000
applyPuvot(L*U) =
       4.000       3.000
       6.000       3.000
R =
       0.000       0.000
       0.000       0.000
The error is about        0.000.
A + A =
       8.000       6.000
      12.000       6.000
A*A =
      34.000      21.000
      42.000      27.000
A.inverse() =
      -0.500       0.500
       1.000      -0.667
A*A.inverse() =
       1.000       0.000
       0.000       1.000
A.det() = -6.0
A*3 =
      12.000       9.000
      18.000       9.000
A =
       4.000       3.000
       6.000       3.000
A**2 =
      34.000      21.000
      42.000      27.000
A**2 =
      34.000      21.000
      42.000      27.000
A**0 =
       1.000       0.000
       0.000       1.000
A**3 =
     262.000     165.000
     330.000     207.000
A**4 =
    2038.000    1281.000
    2562.000    1611.000
A**5 =
   15838.000    9957.000
   19914.000   12519.000
A**6 =
  123094.000   77385.000
  154770.000   97299.000
A**7 =
  956686.000  601437.000
 1202874.000  756207.000
A**8 =
    7435366.000    4674369.000
    9348738.000    5877243.000
A**9 =
   57787678.000   36329205.000
   72658410.000   45677943.000
A**10 =
  449125942.000  282350649.000
  564701298.000  355009059.000
A**(-1) =
      -0.500       0.500
       1.000      -0.667
A**(-2) =
       0.750      -0.583
      -1.167       0.944
A**(-2)*A**2 =
       1.000       0.000
       0.000       1.000
-------------------------------------------*/





Posted by Scripter
,

        A = [1, 2; 3, 4]
        B = [2, 1; -1, 2]

로 주어진 두 2x2 행렬 A, B 에 대하여

        AB, BA. transpose(A), transpose(A) B
        det(A), inverse(A),
        inverseA) A, A inverse(A)

를 각각 구하는 방법을 여러 가지 도구

        Mathematica, Maxima, Octave, Scipy

들을 각각 이용하여 알아본다.
,


* Mathematica 를 이용하여 행렬 계산하기 (행렬 곱셈, 전치행렬, 행렬식, 역행렬 등)
  (참고: Mathematica 에서 행렬 곱샘 연산자는 .(점) 이다.)

 




* Maxima 를 이용하여 행렬 계산하기 (행렬 곱셈, 전치행렬, 행렬식, 역행렬 등)
  (참고: Maxima 애서도 Mathematica 에서와 마찬가지로 행렬 곱샘 연산자는 .(점) 이다.)
** 행렬의 생성과 곱셈

 



** 전치행렬, 행렬식, 역행렬

 





* Octave 를 이용하여 행렬 계산하기 (스칼라배, 합, 차 등)
** Octave 소스
A = [1, 2; 3, 4]
B = [2, 1; -1, 2]
A*B, B*A
A', A'*B
transpose(A), transpose(A)*B
det(A), inverse(A), A^(-1), A^-1
A^-1 * A, A * A^-1
inverse(A) * A, A * inverse(A)


** Octave 명령 창에서 행렬 A, B 생성하고 행렬 곱셈 계산하기

 



** Octave 명령 창에서 전치행렬, 행렬식, 역행렬 구하기



** Octave 명령 창에서 행렬 곱셈으로 역행렬 검증하기

 




* Python 2.7 & Scipy를 이용하여 행렬 계산하기 (행렬 곱셈, 전치행렬, 행렬식, 역행렬 등)
** 파이썬 소스
import numpy as np
import scipy as sp
from scipy import mat
from scipy import linalg

A = mat( "[1, 2; 3, 4]" )
B = mat( "[2, 1; -1, 2]" )
A; B
A*B; B*A
np.transpose(A); np.transpose(A)*B
linalg.det(A); linalg.inv(A); A.I
A*(A.I); (A.I)*A


** 위의 소스를 파일로 저장하지 말고, Python 인터프리터 실행 창에서 한 줄씩 입력한다.

 





* Python 2.6 & 2.7 에서 동작하는 분수만으로 이루어진 정방행렬의
   행렬식, 역행렬 구하는 함수를 구현해 보았다.
   (참고: scipy.linalg 모듈은 분수를 부동소수점수로 바꾸어 계산하므로
            역행렬에서  분수 성질이 없어진다.)

"""
  Filename: TestFraction.py

            Test fraction calculations, wgich works on Python 2.6 or 2.7.

   Execute: python TestFraction.py
      Date: 2011. 10. 10
"""

from fractions import *
import numpy as np
import scipy as sp
from scipy import *

def evalFraction(x):
 return x.numerator/float(x.denominator)

def printMatrix(msg, m):
 if msg != None and len(msg) > 0:
  print msg
 print "%s" % m

def minorMatrix(m, x, y):
 nr, nc = m.shape
 t = []
 for i in range(0, nr - 1):
  tmp = []
  for j in range(0, nc - 1):
   if i < x:
    if j < y:
     u = m[i, j]
     tmp.append(u)
    else:
     u = m[i, j+1]
     tmp.append(u)
   else:
    if j < y:
     u = m[i+1, j]
     tmp.append(u)
    else:
     u = Fraction(m[i+1, j+1])
     tmp.append(u)
  t.append(tmp)
 t2 = matrix(t)
 return t2
 
def det(m):
 nr, nc = m.shape
 if nr != nc:
      print "Caught TypeError"
      return None
 if nr == 1:
  return m[0, 0]
 elif nr == 2:
          return m[0, 0]*m[1, 1] - m[0, 1]*m[1, 0]
 else:
  sum = 0
  sign = 1
  for j in range(0, nc):
   minor = minorMatrix(m, 0, j)
   sum = sum + sign*m[0, j]*det(minor)
   sign = -sign
  return sum
 return None

def inverse(m):
 nr, nc = m.shape
 if nr != nc:
      print "Caught TypeError"
      return None
 if nr == 1:
  return matrix([[1/m[0, 0]]])
 elif nr == 2:
          d = [1, 1] - m[0, 1]*m[1, 0]
          return matrix( [[m[1, 1]/d, m[0,1]/d], [m[1, 0]/d, m[1, 1]/d]] )
 else:
  d = det(m)
  sign = 1
  t = []
  for j in range(0, nc):
   tmp = []
   for i in range(0, nr):
       minor = minorMatrix(m, i, j)
       sign = (-1)**(i + j)
       v = sign*det(minor)
       tmp.append(v/d)
   t.append(tmp)
  t2 = matrix(t)
  return t2
 return None

def hilbertMatrix(n):
 if n <= 0:
  return None
 t = []
 for i in range(0, n):
  tmp = []
  for j in range(0, n):
      tmp.append(Fraction(1, i + j + 1))
  t.append(tmp)
 t2 = matrix(t)
 return t2


z = Fraction(1, 2)
w = Fraction("5/4")

A = mat([[Fraction(1,5), Fraction(3,5)], [Fraction(3,5), Fraction(4,5)]])
B = mat([[Fraction(4,3), Fraction(-1,3)], [Fraction(2,3), Fraction(7,3)]])
printMatrix("A = ", A)
printMatrix("B = ", B)
printMatrix("A + B = ", A + B)
printMatrix("A - B = ", A - B)
printMatrix("A * B = ", A * B)
printMatrix("A / B = ", A / B)
printMatrix("A**2 = ", A**2)
printMatrix("A**3 = ", A**3)
printMatrix("B**-1 = ", B**-1)
printMatrix("B*B**-1 = ", B*B**-1)
printMatrix("B.transpose() = ", B.transpose())

print "B[0, 0] = %s" % (B[0, 0])
print "B[0, 1] = %s" % (B[0, 1])
print "B[1, 0] = %s" % (B[1, 0])
print "B[1, 1] = %s" % (B[1, 1])

B[0][0] = Fraction(5, 1) 
B[0][0] = 50
printMatrix("Changed: B = ", B)
print "  ---> det(B) = %s" % det(B)
B[0,0] = 80
printMatrix("Changed again: B = ", B)
print "  ---> det(B) = %s" % det(B)

C = mat([ [Fraction(1,1), Fraction(1,2), Fraction(1,3)],
          [Fraction(1,2), Fraction(1,3), Fraction(1,4)], 
          [Fraction(1,3), Fraction(1,4), Fraction(1,5)] ])
printMatrix("C = ", C)
v = det(C)
print "  ---> det(C) = %s" % v
print "       evalFraction(det(C)) = %s" % evalFraction(v)

from scipy import linalg
print "Cehck again by using scipy.linalg(): "
print "       linalg.det(C) = %s" % linalg.det(C)

D = inverse(C)
print "inverse(C) = \n%s" % D
printMatrix("inverse(C)*C = ", D*C)
printMatrix("C*inverse(C) = ", C*D)
printMatrix("linalg.inv(C) = ", linalg.inv(C))
printMatrix("linalg.inv(C)*C = ", linalg.inv(C)*C)

H = hilbertMatrix(4)
printMatrix("H = ", H)
v = det(H)
print "  ---> det(H) = %s" % v
print "       evalFraction(det(H)) = %s" % evalFraction(v)
print "Cehck again by using scipy.linalg(): "
print "       linalg.det(H) = %s" % linalg.det(H)
G = inverse(H)
print "inverse(H) = \n%s" % G
printMatrix("inverse(H)*H = ", G*H)
printMatrix("H*inverse(H) = ", H*G)
printMatrix("linalg.inv(H) = ", linalg.inv(H))
printMatrix("linalg.inv(H)*H = ", linalg.inv(H)*H)

"""
Execute Result:
A =
[[1/5 3/5]
 [3/5 4/5]]
B =
[[4/3 -1/3]
 [2/3 7/3]]
A + B =
[[23/15 4/15]
 [19/15 47/15]]
A - B =
[[-17/15 14/15]
 [-1/15 -23/15]]
A * B =
[[2/3 4/3]
 [4/3 5/3]]
A / B =
[[3/20 -9/5]
 [9/10 12/35]]
A**2 =
[[2/5 3/5]
 [3/5 1]]
A**3 =
[[11/25 18/25]
 [18/25 29/25]]
B**-1 =
[[ 0.7  0.1]
 [-0.2  0.4]]
B*B**-1 =
[[1.0 0.0]
 [-5.55111512313e-17 1.0]]
B.transpose() =
[[4/3 2/3]
 [-1/3 7/3]]
B[0, 0] = 4/3
B[0, 1] = -1/3
B[1, 0] = 2/3
B[1, 1] = 7/3
Changed: B =
[[50 50]
 [2/3 7/3]]
  ---> det(B) = 250/3
Changed again: B =
[[80 50]
 [2/3 7/3]]
  ---> det(B) = 460/3
C =
[[1 1/2 1/3]
 [1/2 1/3 1/4]
 [1/3 1/4 1/5]]
  ---> det(C) = 1/2160
       evalFraction(det(C)) = 0.000462962962963
Cehck again by using scipy.linalg():
       linalg.det(C) = 0.000462962962963
inverse(C) =
[[9 -36 30]
 [-36 192 -180]
 [30 -180 180]]
inverse(C)*C =
[[1 0 0]
 [0 1 0]
 [0 0 1]]
C*inverse(C) =
[[1 0 0]
 [0 1 0]
 [0 0 1]]
linalg.inv(C) =
[[   9.  -36.   30.]
 [ -36.  192. -180.]
 [  30. -180.  180.]]
linalg.inv(C)*C =
[[1.0 0.0 0.0]
 [0.0 1.0 0.0]
 [0.0 0.0 1.0]]
H =
[[1 1/2 1/3 1/4]
 [1/2 1/3 1/4 1/5]
 [1/3 1/4 1/5 1/6]
 [1/4 1/5 1/6 1/7]]
  ---> det(H) = 1/6048000
       evalFraction(det(H)) = 1.65343915344e-07
Cehck again by using scipy.linalg():
       linalg.det(H) = 1.65343915344e-07
inverse(H) =
[[16 -120 240 -140]
 [-120 1200 -2700 1680]
 [240 -2700 6480 -4200]
 [-140 1680 -4200 2800]]
inverse(H)*H =
[[1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]]
H*inverse(H) =
[[1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]]
linalg.inv(H) =
[[   16.  -120.   240.  -140.]
 [ -120.  1200. -2700.  1680.]
 [  240. -2700.  6480. -4200.]
 [ -140.  1680. -4200.  2800.]]
linalg.inv(H)*H =
[[1.0 0.0 0.0 -3.5527136788e-15]
 [0.0 1.0 -5.68434188608e-14 2.84217094304e-14]
 [0.0 0.0 1.0 1.13686837722e-13]
 [0.0 0.0 5.68434188608e-14 1.0]]
"""







 

Posted by Scripter
,

        A = [1, 2, 3; 4, 5. 6]
        B = [3, 0, 1; -1, 2, -2]

로 주어진 두 2x3 행렬 A, B 에 대하여

        2A, 3B. 2A + 3B. 2A - 3B,
        A의 첫째 행, B의 둘째 행, A의 첫째 행과 B의 둘째 행의 3배의 합,
        A의 첫째 행 첫째 열 요소, B의 둘째 행 셋째 열 요소, 
        A의 첫째 행 첫째 열 요소의 5배와 B의 둘째 행 셋째 열 요소의 차

를 각각 구하는 방법을 여러 가지 도구

        Mathematica, Maxima, Octave, Scipy

들을 각각 이용하여 알아본다.
,


* Mathematica 를 이용하여 행렬 계산하기 (스칼라배, 합, 차 등)




* Maxima 를 이용하여 행렬 계산하기 (스칼라배, 합, 차 등)





* Octave 를 이용하여 행렬 계산하기 (스칼라배, 합, 차 등)
** Octave 소스
A = [1, 2, 3; 4, 5. 6]
B = [3, 0, 1; -1, 2, -2]
2*A, 3*B, 2*A + 3*B, 2*A - 3*B
A(1,:), 3*B(2,:), A(1,:)+3*B(2,:)
5*A(1,1), B(2,3), 5*A(1,1)-B(2,3)


** Octave 명령 창에서 행렬 A, B 생성하기



** Octave 명령 창에서 기본적인 행렬 계산 (스칼라배, 합, 차 등)




* Python 2.7 & Scipy를 이용하여 행렬 계산하기 (스칼라배, 합, 차 등)
** 파이썬 소스
import numpy as np
import scipy as sp
from scipy import *
A = mat( "[1, 2, 3; 4, 5, 6]" )
B = mat( "[3, 0, 1; -1, 2, 3]" )
A; B
2*A; 3*B; 2*A + 3*B; 2*A - 3*B
A[0]; 3*B[1]; A[0] + 3*B[1]
5*A[0,0]; B[1, 2]; 5*A[0,0] - B[1, 2


** 위의 소스를 파일로 저장시키지 않고, Python 인터프리터 실행 창에서 한 줄씩 입력한다.




* Lua 5.1.4 & LuaMatrix 0.2.9 를 이용하여 행렬 계산하기 (스칼라배, 합, 차 등)
   (참고1: LuaMatrix 는 http://lua-users.org/wiki/LuaMatrix 에서 구할 수 있음)
   (참고2: http://numlua.luaforge.net/ 에서 numlua 패키지를 받아서 설치해도 된다.)
**  Lua 소스

--// Filename: TestMatrix-01.lua
-- //                Using the matrix class given at http://lua-users.org/wiki/LuaMatrix
-- //  Execute:  lua TestMatrix-01.lua

local matrix = require "lua_matrix"

function printMatrix(msg, a)
    if type(a) == "number" then
        print( msg .. a )
        return
    end
    if type(msg) == "string" and #(msg) > 0 then
        print( msg .. "[ ")
    end
    print( a:tostring() .. " ]" )
end

function matrix.getRow(a, k)
    local n = #a[1]
    return matrix.subm(a, k, 1, k, n)
end

function matrix.row(a, k)
    local n = #a[1]
    return matrix.subm(a, k, 1, k, n)
end

function matrix.col(a, k)
    local n = #a
    return matrix.subm(a, 1, k, n, k)
end

local A, B, C, D

-- instantiate of matrices
A = matrix:new({{1, 2, 3}, {4, 5, 6}})
printMatrix( "A = ", A )
B = matrix:new({{3, 0, 1}, {1, 2, -2}})
printMatrix( "B = ", B )
printMatrix( "B + B = ", B + B )
printMatrix( "B - B = ", B - B )
printMatrix( "B:transpose() * B = ", B:transpose() * B )
printMatrix( "3 * B = ", 3 * B )
printMatrix( "0.1 * B = ", 0.1 * B )
local x, y = matrix.size(B)
print( "matrix.size(B) = ".. x .. "x" .. y)

C = matrix.copy( 2*B )
printMatrix( "C = ", C )
C = (3*B):copy()
printMatrix( "C = ", C )

printMatrix( "2*A = ", 2*A )
printMatrix( "3*B = ", 3*B )
printMatrix( "2*A + 3*B = ", 2*A + 3*B )
printMatrix( "2*A - 3*B = ", 2*A - 3*B )
print( "B:getelement(2,3) = ".. B:getelement(2,3))
print( "More simply, B[2][3] = ".. B[2][3])
print( "5*A:getelement(1,1) - B:getelement(2,3) = ".. (5*A:getelement(1,1) - B:getelement(2,3)))
print( "More simply, Simply, *A[1][1] - B[2][3] = ".. (5*A[1][1] - B[2][3]))
printMatrix( "matrix.subm(A, 1, 1, 1, 3) = ", matrix.subm(A, 1, 1, 1, 3))
printMatrix( "matrix.subm(B, 2, 1, 2, 3) = ", matrix.subm(B, 2, 1, 2, 3))
printMatrix( "matrix.row(B, 2) = ", matrix.row(B, 2))
printMatrix( "3*matrix.getRow(B, 2) = ", 3*matrix.getRow(B, 2))
printMatrix( "More simply, 3*matrix.row(B, 2) = ", 3*matrix.row(B, 2))
printMatrix( "matrix.col(B, 2) = ", matrix.col(B, 2))
printMatrix( "B/2 = ", B/2 )
printMatrix( "1/2*B = ", 1/2*B )

--[[
Execute Result:
A = [
1       2       3
4       5       6 ]
B = [
3       0       1
1       2       -2 ]
B + B = [
6       0       2
2       4       -4 ]
B - B = [
0       0       0
0       0       0 ]
B:transpose() * B = [
10      2       1
2       4       -4
1       -4      5 ]
3 * B = [
9       0       3
3       6       -6 ]
0.1 * B = [
0.3     0       0.1
0.1     0.2     -0.2 ]
matrix.size(B) = 2x3
C = [
6       0       2
2       4       -4 ]
C = [
9       0       3
3       6       -6 ]
2*A = [
2       4       6
8       10      12 ]
3*B = [
9       0       3
3       6       -6 ]
2*A + 3*B = [
11      4       9
11      16      6 ]
2*A - 3*B = [
-7      4       3
5       4       18 ]
B:getelement(2,3) = -2
More simply, B[2][3] = -2
5*A:getelement(1,1) - B:getelement(2,3) = 7
More simply, Simply, *A[1][1] - B[2][3] = 7
matrix.subm(A, 1, 1, 1, 3) = [
1       2       3 ]
matrix.subm(B, 2, 1, 2, 3) = [
1       2       -2 ]
matrix.row(B, 2) = [
1       2       -2 ]
3*matrix.getRow(B, 2) = [
3       6       -6 ]
More simply, 3*matrix.row(B, 2) = [
3       6       -6 ]
matrix.col(B, 2) = [
0
2 ]
B/2 = [
1.5     0       0.5
0.5     1       -1 ]
1/2*B = [
1.5     0       0.5
0.5     1       -1 ]
--]]





 

Posted by Scripter
,
3차원 직교좌표계에서 구면(sphere)의 매개방정식은
\, x = x_0 + r \sin \theta \; \cos \varphi
\, y = y_0 + r \sin \theta \; \sin \varphi \qquad (0 \leq \varphi \leq 2\pi \mbox{ and } 0 \leq \theta \leq \pi ) \,
\, z = z_0 + r \cos \theta \,

으로 주어진다. 이 매개방정식을 이용하여 구면을 여러가지 그리기 도구

          Mathemarica, Maxima, Grapher, Gnuplot, Octave, Matplotlib

들로 각각 그려보자.        



* 윈도우 XP 에서 Mathematica 8 을 이용하여 그리기





* 윈도우 XP 에서 wxMaxima 를 이용하여 그리기
** 명령 입력



** 위의 명령으로 별도의 창에 그려진 곡면





* Mac OS X Lion 에서 Grapher 를 이용하여 그리기





* 윈도우 XP 에서 Gnuplot 을 이용하여 그리기
** Gnuplot 소스

#
# parametricSphere.dem

set term win
set parametric
set isosamples 80, 30
set hidden
set key below

set title "Parametric Sphere"
set urange [0:2*pi]
set vrange [-pi/2:pi/2]
set ztics nomirror -2.0, 0.5, 2.0
set view 45,50
a = 3
splot a*cos(u)*cos(v), a*sin(u)*cos(v), a*sin(v)



** Gnuplot 창에 위의 소스를 입력하기



** 위의 명령으로 Gnuplot 이 그려준 곡면




* 윈도우 XP 에서 Octave 3.2.4 를 이용하하여 곡면 그리기
** Octave 소스
a = 3;
x = @(u, v) a.*cos (u) .* cos(v);
y = @(u, v) a.*sin (u) .* cos(v);
z = @(u, v) a.*sin(v);
ezmesh (x, y, z, [0, 2*pi, -pi/2, pi/2], 50);


** 위의 명령으로 Octave 가 그려준 곡면




* Matplotlib 를 이용하여 곡면 그리기
** 파이썬 소스
#!/usr/bin/env python

from mpl_toolkits.mplot3d.axes3d import Axes3D
import matplotlib.pyplot as plt

# imports specific to the plots in this example
import numpy as np
from matplotlib import cm

# Twice as wide as it is tall.
fig = plt.figure(figsize=plt.figaspect(0.7))

#---- First subplot
ax = fig.add_subplot(1, 1, 1, projection='3d')
U = np.arange(0, 2*np.pi, 0.1)
V = np.arange(0, 2*np.pi, 0.1)
U, V = np.meshgrid(U, V)
a = 3
X = a*np.cos(U)*np.cos(V)
Y = a*np.sin(U)*np.cos(V)
Z = a*np.sin(V)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet,
        linewidth=0, antialiased=False)
ax.set_zlim3d(-2.01, 2.01)

fig.colorbar(surf, shrink=0.5, aspect=10)

plt.show()




** 위의 소스를 실행시켜서 그린 곡면




 

Posted by Scripter
,
3차원 직교좌표계에서 토러스(torus)의 매개방정식은
x(u, v) =  (R + r \cos{v}) \cos{u} \,
y(u, v) =  (R + r \cos{v}) \sin{u} \,
z(u, v) =  r \sin{v} \,
으로 주어진다. 이 매개방정식을 이용하여 torus 를 여러가지 그리기 도구

          Mathemarica, Maxima, Grapher, Gnuplot, Octave, Matplotlib

들로 각각 그려보자.        



* 윈도우 XP 에서 Mathematica 8 을 이용하여 그리기





* 윈도우 XP 에서 wxMaxima 를 이용하여 그리기
** 명령 입력



** 위의 명령으로 별도의 창에 그려진 곡면





* Mac OS X Lion 에서 Grapher 를 이용하여 그리기





* 윈도우 XP 에서 Gnuplot 을 이용하여 그리기
** Gnuplot 소스
#
# parametricTorus.dem

set term win
set parametric
set isosamples 80, 30
set hidden
set key below

set title "Parametric Torus"
set urange [0:2*pi]
set vrange [0:2*pi]
set ztics nomirror -2.0, 0.5, 2.0
set view 45,50
a = 5
b = 2
splot (a+ b*cos(v))*cos(u), (a + b*cos(v))*sin(u), b*sin(v)


** Gnuplot 창에 위의 소스를 입력하기



** 위의 명령으로 Gnuplot 이 그려준 곡면




* 윈도우 XP 에서 Octave 3.2.4 를 이용하하여 곡면 그리기
** Octave 소스
a = 5;
b = 2;
fx = @(u, v) (a + b.*cos(v)).*cos(u);
fy = @(u, v) (a + b.*cos(v)).*sin(u);
fz = @(u, v) b.*sin(v);
ezmesh (fx, fy, fz, [-2*pi, 2*pi, -2*pi, 2*pi], 50);


** Octave 실행 창에 명령 입력하기




** 위의 명령으로 Octave 가 그려준 곡면





* Matplotlib 를 이용하여 곡면 그리기
1) 두 가지 색으로 칠하기
** 파이썬 소스

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
U = np.arange(-2*np.pi, 2*np.pi, 0.2)
ulen = len(U)
V = np.arange(-2*np.pi, 2*np.pi, 0.2)
vlen = len(V)
U, V = np.meshgrid(U, V)
a = 5
b = 2
X = (a + b*np.cos(V))*np.cos(U)
Y = (a + b*np.cos(V))*np.sin(U)
Z = np.sin(V)

colortuple = ('y', 'b')
colors = np.empty(X.shape, dtype=str)
for v in range(vlen):
    for u in range(ulen):
        colors[u, v] = colortuple[(u + v) % len(colortuple)]

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=colors,
        linewidth=0, antialiased=False)

ax.set_zlim3d(-1, 1)
ax.w_zaxis.set_major_locator(LinearLocator(6))
ax.w_zaxis.set_major_formatter(FormatStrFormatter('%.03f'))

plt.show()


** 위의 소스를 실행시켜서 그린 곡면



2) 선으로만 그리기
** 파이썬 소스

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
U = np.arange(-2*np.pi, 2*np.pi, 0.2)
ulen = len(U)
V = np.arange(-2*np.pi, 2*np.pi, 0.2)
vlen = len(V)
U, V = np.meshgrid(U, V)
a = 5
b = 2
X = (a + b*np.cos(V))*np.cos(U)
Y = (a + b*np.cos(V))*np.sin(U)
Z = np.sin(V)
ax.plot_wireframe(X, Y, Z, rstride=3, cstride=3)

plt.show()



** 위의 소스를 실행시켜서 그린 곡면




3) 높이에 따라 다른 색으로 칠하기
** 파이썬 소스

#!/usr/bin/env python

from mpl_toolkits.mplot3d.axes3d import Axes3D
import matplotlib.pyplot as plt

# imports specific to the plots in this example
import numpy as np
from matplotlib import cm

# Twice as wide as it is tall.
fig = plt.figure(figsize=plt.figaspect(0.7))

#---- First subplot
ax = fig.add_subplot(111, projection='3d')
U = np.arange(0, 2*np.pi, 0.1)
V = np.arange(0, 2*np.pi, 0.1)
U, V = np.meshgrid(U, V)
a = 5
b = 2
X = (a + b*np.cos(V))*np.cos(U)
Y = (a + b*np.cos(V))*np.sin(U)
Z = b*np.sin(V)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet,
        linewidth=0, antialiased=False)
ax.set_zlim3d(-2.01, 2.01)

fig.colorbar(surf, shrink=0.5, aspect=10)

plt.show()



** 위의 소스를 실행시켜서 그린 곡면




Posted by Scripter
,