1. mpir 은 gmp 대신사용하는 (C/C++ 언어용) 긴 자리 수치 처리를 위한 기본 연산 라이브러리이다.

   자리수가 매우 긴 정수, 유리수, 소수점수를 계산할 수 있다.

2. xmpir 은 (C 언어용 긴 자리 수치 라이브러리인) mpir 의 래퍼(wrapper) 이다.

3. xmpir 은  xmpir 다운로드 에서 구할 수 있다.

(주의 사항. dl4windows.dll 파일이 존재하는 폴더의 경로명에 #문자가 있으면 컴파일은 되나 실행 시에 에러에 걸린다. 그 이유는 xmpir 이 dl4windows.dll 파일을 찾을 때 URL 주소를 적용해서 찾기 때문이다.)

 

실행에 필요한 *.dll 파일들은 (현재 경로 또는) 환경변수 PATH 에 결린 경로의 폴더에 존재해야 한다.

  • dl4windows.dll  : 윈도우 계열의 닷넷 에서 실행될 때 xmpir 이 찾는 파일
  • dl4linux.dll  : 리눅스 계열의 mono 에서 실행될 때 xmpir 이 찾는 파일
  • xmpir32.dll : 32 비트 윈도우 또는 리눅스에서 실행될 때 PATH 걸린 폴더에 있어야 하는 파일
  • xmpir64.dll : 64 비트 윈도우 또는 리눅스에서 실행될 때 PATH 걸린 폴더에 있어야 하는 파일
  • src\xmpir,cs : 컴파일할 때 함께 사용되어야 하는 파일

 

demo 폴더에서 demo,cs 컴파일하기

    Prompt> csc demo.cs ..\src\xmpir.cs

 

xmpir 을 이용하는 예제 소스 파일 (파일명: demo.cs)

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Diagnostics;
class MyClass
{
    [STAThread]
    static void Main(string[] args)
    {
        mpir.mpz_t f = mpir.mpz_init_set_ui(1);
        int i;
        for(i=2; i<=30; i++)
            mpir.mpz_mul_si(f, f, i);
        System.Console.Write("30! = ");
        System.Console.WriteLine(mpir.mpz_get_string(10,f));
        mpir.mpz_clear(f);        
    }
}

 

실행 결과: 30! = 265252859812191058636308480000000

 

Posted by Scripter
,

음이 아닌 실수 A 의 평방근 sqrt(A) 를 구하는 Heron 의 방법:

        반복함수  g(x) = (x + A/x) / 2   를 이용

 

실수 A 의 n제곱근 root(n, A) 를 구하는 Newton-Raphson 의 방법

        반복함수  g(x) = ((n-1)*x + A/(x**(n - 1))) / n    를 이용

n = 2 인 경우에는 Newton-Raphson 의 방법이 Heron 의 방법과 동일하다.

(참조. http://en.wikipedia.org/wiki/Newton's_method )

 

C# 언어에는 System 모듈에 지수 계산 함수 Math.Pow(double, double) 가 이미 구현되어 있다. 하지만 차후 필요한 데가 있을 것 같아서 이와 유사한 n 제곱 함수와 n 제곱근 함수를 구현해 보았다.

지수가 정수인 거듭제곱을 계산하는  함수도 nPow(), gPow, mPow() 세 개 구현해 놓았는데, 이들 세 함수는 절차적 언어의 성능상 재귀호출이 아니고 단순 반복 기법을 사용하는 함수이다. 이 세 함수 중 mPow() 의 성능이 가장 우수하다. 큰 지수의 경우 for 반복문의 반복회수를 따져 보면 성능 비교를 할 수 있을 것이다. (성능 비교를 위해 세 가지를 모두 소스에 남겨 두었다.) mPow() 함수는 n 제곱근을 구하는 재귀함수 newtonNthRoot(int, double) 의 구현에 사용되기도 한다. if ... else ... 구문이 많아 소스가 복잡하게 보일지 모르겠으나 이는 밑수나 지수가 음수이거나 0인 경우의 처리를 위함이다. 구현된 모든 함수의 구현에는 예외상황(예를 들어, 음수의 짝수 제곱근 같은 예외상황) 처리 과정이 있다.

아래의 소스는 대부분 버전의 비쥬얼 스튜디오의 C# 컴파일러로 컴파일 되고 실행되게 작성된 소스이다.

소스 첫 부분에

        private const int MAX_ITER = 20000;
        private const double M_EPSILON = 1.0e-15;

라고 선언하였으니 변수 MAX_ITER 와 M_EPSILON 는 (타입을 갖는) 상수로 선언되었다. const 예약어가 붙으면 static 예약어는 동시에 붙일 수 없다. Java 언어로는 상수를 선언할 방법이 없지만 C# 언어로는 이와 같이 const 예약어(키워드)를 이용하여 상수를 선언할 수 있다.

// Filename: TestNthRootApp.cs
//
//            Approximate square roots, cubic roots and n-th roots of a given number.
//
// Compile: csc TestNthRootApp.cs
// Execute: TestNthRootApp
//
// Date: 2013. 1. 6.
// Copyright (c) 2013 PH Kim  (pkim __AT__ scripts.pe.kr)


using System;

namespace TestApproximate
{

    public class TestNthRootApp {

        private const int MAX_ITER = 20000;
        private const double M_EPSILON = 1.0e-15;

        /**
         * Compute the n-th root of x to a given scale, x > 0.
         */
        public static double nPow(double a, int n) {
            if (n > 0) {
                if (n == 1)
                    return a;
                else {
                    if (a == 0.0 || a == 1.0) {
                        return a;
                    }
                    else if (a == -1.0) {
                        if (n % 2 == 1)
                            return -1.0;
                        else
                            return 1.0;
                    }
                    else if (a < 0.0) {
                        if (n % 2 == 1)
                            return -nPow(-a, n);
                        else
                            return nPow(-a, n);
                    }
                    else {
                        double y = 1.0;
                        for (int i = 0; i < n; i++) {
                            y *= a;
                        }
                        return y;
                    }
                }
            }
            else if (n == 0) {
                return 1.0;
            }
            else {      //  when n < 0
                if (a == 0.0)
                    throw new Exception("Negative powering exception of zero.");
                else {
                     if (n == -1)
                         return 1.0/a;
                     else
                         return 1.0/nPow(a, -n);
                 }
             }
        }

 

        /**
         * Compute the n-th root of x to a given scale, x > 0.
         */
        public static double gPow(double a, int n) {
            if (n > 0) {
                if (n == 1)
                    return a;
                else {
                    if (a == 0.0 || a == 1.0) {
                        return a;
                    }
                    else if (a == -1.0) {
                        if (n % 2 == 1)
                            return -1.0;
                        else
                            return 1.0;
                    }
                    else if (a < 0.0) {
                        if (n % 2 == 1)
                            return -gPow(-a, n);
                        else
                            return gPow(-a, n);
                    }
                    else {

                        double y = 1.0;
                        double r = a;
                        int m = 8*4 - 1;            ///  8*sizeof(int) - 1;
                        int one = 1;
                        for (int i = 0; i < m; i++) {
                            if ((n & one) == 0) {
                                y *= 1.0;
                            }
                            else {
                                y *= r;
                            }
                            r = r*r;
                            one <<= 1;
                            if (one > n)
                                break;
                        }
                        return y;
                    }
                }
            }
            else if (n == 0) {
                return 1.0;
            }
            else {      //  when n < 0
                if (a == 0.0)
                    throw new Exception("Negative powering exception of zero.");
                else {
                    if (n == -1)
                        return 1.0/a;
                    else
                        return 1.0/gPow(a, -n);
                }
            }
        }


        /**
         * Compute the n-th root of x to a given scale, x > 0.
         */
        public static double mPow(double a, int n) {
            if (n > 0) {
                if (n == 1)
                    return a;
                else {
                    if (a == 0.0 || a == 1.0) {
                        return a;
                    }
                    else if (a == -1.0) {
                        if (n % 2 == 1)
                            return -1.0;
                        else
                            return 1.0;
                    }
                    else if (a < 0.0) {
                        if (n % 2 == 1)
                            return -mPow(-a, n);
                        else
                            return mPow(-a, n);
                    }
                    else {

                        double y = 1.0;
                        double r = a;
                        int m = n;
                        while (m > 0) {
                            if ((m & 0x1) == 1) {
                                y *= r;
                            }
                            r = r*r;
                            m >>= 1;
                        }
                        return y;
                    }
                }
            }
            else if (n == 0) {
                return 1.0;
            }
            else {      //  when n < 0
                if (a == 0.0)
                    throw new Exception("Negative powering exception of zero.");
                else {
                    if (n == -1)
                        return 1.0/a;
                    else
                        return 1.0/mPow(a, -n);
                }
            }
        }

 

        /**
         * Compute the square root of x to a given scale, x > 0.
         */
        public static double heronSqrt(double a) {
            if (a < 0.0) {
                throw new Exception("Cannot find the sqrt of a negative number.");
            }
            else if (a == 0.0 || a == 1.0) {
                return a;
            }
            else {
                double x1 = a;
                double x2 = (x1 + a/x1)/2.0;
                double er = x1 - x2;
                int counter = 0;
                while (x1 + er != x1) {
                    x1 = x2;
                    x2 = (x1 + a/x1)/2.0;
                    er = x1 - x2;
                    if (Math.Abs(er) <Math.Abs( M_EPSILON*x1))
                        break;
                    counter++;
                    if (counter > MAX_ITER)
                        break;
                }
                if (counter >= MAX_ITER)
                    throw new Exception("Inaccurate sqrt exception by too many iterations.");
                return x2;
            }
        }

        /**
         * Compute the cubic root of x to a given scale, x > 0.
         */
        public static double newtonCbrt(double a) {
            if (a == 0.0 || a == 1.0 || a == -1.0) {
                return a;
            }
            else if (a < 0.0) {
                return -newtonCbrt(-a);
            }
            else {
                double x1 = a;
                double x2 = (2.0*x1 + a/(x1*x1))/3.0;
                double er = x1 - x2;
                int counter = 0;
                while (x1 + er != x1) {
                    x1 = x2;
                    x2 = (2.0*x1 + a/(x1*x1))/3.0;
                    er = x1 - x2;
                    if (Math.Abs(er) <Math.Abs( M_EPSILON*x1))
                        break;
                    counter++;
                    if (counter > MAX_ITER)
                        break;
                }
                if (counter >= MAX_ITER)
                    throw new Exception("Inaccurate cbrt exception by too many iterations.");
                return x2;
            }
        }

        /**
         * Compute the n-th root of x to a given scale, x > 0.
         */
        public static double newtonNthRoot(int n, double a) {
            if (n == 0) {
                return 1.0;
            }
            else if (n == 1) {
                return a;
            }
            else if (n > 0) {
                if (a == 0.0 || a == 1.0) {
                    return a;
                }
                else if (a == -1.0) {
                    if (n % 2 == 1)
                        return a;
                    else
                        throw new Exception("Cannot find the even n-th root of a negative number.");
                }
                else if (a < 0.0) {
                    if (n % 2 == 1)
                        return -newtonNthRoot(n, -a);
                    else
                        throw new Exception("Cannot find the even n-th root of a negative number.");
                }
                else if (a < 1.0) {
                    return 1.0/newtonNthRoot(n, 1.0/a);
                }
                else {
                    double x1 = a;
                    double xn = mPow(x1, n - 1);
                    double x2 = ((n - 1)*x1 + a/xn)/n;
                    double er = x1 - x2;
                    int counter = 0;
                    while (x1 + er != x1) {
                        x1 = x2;
                        xn = mPow(x1, n - 1);
                        x2 = ((n - 1)*x1 + a/xn)/n;
                        er = x1 - x2;
                        if (Math.Abs(er) <Math.Abs( M_EPSILON*x1))
                            break;
                        counter++;
                        if (counter > MAX_ITER)
                            break;
                    }
                    if (counter >= MAX_ITER)
                        throw new Exception("Inaccurate n-th root exception by too many iterations.");
                    return x2;
                }
            }
            else {
                if (a == 0.0) {
                    throw new Exception("Cannot find the negative n-th root of zero.");
                }
                else {
                    return 1.0/newtonNthRoot(-n, a);
                }
            }
        }


        public static void Main(string[] args) {

            double x = 16.0;
            double u = Math.Sqrt(x);

            Console.WriteLine("[ Testing heronSqrt(double) ]--------------------");
            Console.WriteLine("x = " + x );
            Console.WriteLine("u = Sqrt(" + x + ") = " + u );
            double y = heronSqrt(x);
            Console.WriteLine("y = heronSqrt(" + x + ") = " + y );
            Console.WriteLine("y*y = " + y*y );
            Console.WriteLine();

            Console.WriteLine("[ Testing newtonCbrt(double) ]--------------------" );
            x = -216.0;
            Console.WriteLine("x = " + x );
            Console.WriteLine("-Exp(Log(-x)/3.0) = " + -Math.Exp(Math.Log(-x)/3.0) );
            double w = newtonCbrt(x);
            Console.WriteLine("w = newtonCbrt(" + x + ") = " + w );
            Console.WriteLine("w*w*w = " + w*w*w );
            Console.WriteLine();

            x = 729000000000.0;
            Console.WriteLine("x = " + x );
            Console.WriteLine("Exp(Log(x)/3.0) = " + Math.Exp(Math.Log(x)/3.0) );
            w = newtonCbrt(x);
            Console.WriteLine("w = newtonCbrt(" + x + ") = " + w );
            Console.WriteLine("w*w*w = " + w*w*w );
            Console.WriteLine();

            Console.WriteLine("[ Testing newtonNthRoot(int, double) ]--------------------" );
            double z = newtonNthRoot(3, x);
            Console.WriteLine("x = " + x );
            Console.WriteLine("z = newtonNthRoot(3, " + x + ") = " + z );
            Console.WriteLine("z*z*z = " + z*z*z );
            Console.WriteLine();

            x = 12960000000000000000.0;
            z = newtonNthRoot(4, x);
            Console.WriteLine("x = " + x );
            Console.WriteLine("z = newtonNthRoot(4, x) = newtonNthRoot(4, " + x + ") = " + z );
            Console.WriteLine("z*z*z*z = " + z*z*z*z );
            Console.WriteLine();

            x = 1.0/12960000000000000000.0;
            z = newtonNthRoot(4, x);
            Console.WriteLine("x = " + x );
            Console.WriteLine("Exp(Log(x)/4.0) = " + Math.Exp(Math.Log(x)/4.0) );
            Console.WriteLine("z = newtonNthRoot(4, x) = newtonNthRoot(4, " + x + ") = " + z );
            Console.WriteLine("z*z*z*z = " + z*z*z*z );
            Console.WriteLine();


            try {
                x = -4.0;
                Console.WriteLine("[ Test Exception heronSqrt(double) ]--------------------" );
                Console.WriteLine("x = " + x );
                Console.WriteLine("Calculating heronSqrt(" + x + ")" );
                y = heronSqrt(x);
                Console.WriteLine("y = heronSqrt(" + x + ") = " + y );
                Console.WriteLine("y*y = " + y*y );
                Console.WriteLine();
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message + "\n" + "Caught some exception in calculating heronSqrt(" + x + ")");
                Console.WriteLine();
            }


            try {
                x = -4.0;
                Console.WriteLine("[ Test Exception in newtonCbrt(double) ]--------------------" );
                Console.WriteLine("x = " + x );
                Console.WriteLine("Calculating newtonCbrt(" + x + ")" );
                y = newtonCbrt(x);
                Console.WriteLine("y = newtonCbrt(" + x + ") = " + y );
                Console.WriteLine("y*y*y = " + y*y*y );
                Console.WriteLine();
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message + "\n" + "Caught some exception in calculating newtonCbrt(" + x + ")");
                Console.WriteLine();
            }


            Console.WriteLine("[ Test calculations by powering ]-----------------------------" );
            x = 200.0;
            z = newtonNthRoot(10, x);
            Console.WriteLine("x = " + x );
            Console.WriteLine("Exp(Log(x)/10.0) = " + Math.Exp(Math.Log(x)/10.0) );
            Console.WriteLine("z = newtonNthRoot(10, x) = newtonNthRoot(10, " + x + ") = " + z );
            Console.WriteLine("Pow(z, 10) = " + Math.Pow(z, 10) );
            Console.WriteLine();

            x = 3001.0;
            z = newtonNthRoot(99, x);
            Console.WriteLine("x = " + x );
            Console.WriteLine("Exp(Log(x)/99.0) = " + Math.Exp(Math.Log(x)/99.0) );
            Console.WriteLine("z = newtonNthRoot(99, x) = newtonNthRoot(99, " + x + ") = " + z );
            Console.WriteLine("Pow(z, 99) = " + Math.Pow(z, 99) );
            Console.WriteLine();

            x = 3001.0;
            z = newtonNthRoot(-99, x);
            Console.WriteLine("x = " + x );
            Console.WriteLine("Exp(Log(x)/-99.0) = " + Math.Exp(Math.Log(x)/-99.0) );
            Console.WriteLine("z = newtonNthRoot(-99, x) = newtonNthRoot(-99, " + x + ") = " + z );
            Console.WriteLine("1.0/Pow(z, 99) = " + 1.0/Math.Pow(z, 99) );
            Console.WriteLine();


            Console.WriteLine("2.1**2.1 = Pow(2.1, 2.1) = "  + Math.Pow(2.1, 2.1) );
            Console.WriteLine("2.1**(-2.1) = Pow(2.1, -2.1) = "  + Math.Pow(2.1, -2.1) );
            Console.WriteLine("2.1**2.1 * 2.1**(-2.1) = Pow(2.1, 2.1) * Pow(2.1, -2.1) = "  + Math.Pow(2.1, 2.1)*Math.Pow(2.1, -2.1) );
            Console.WriteLine("2.1**2.1 = Exp(2.1*Log(2.1)) = "  + Math.Exp(2.1*Math.Log(2.1)) );
            Console.WriteLine("2.1**(-2.1) = Exp(-2.1*Log(2.1)) = " + Math.Exp(-2.1*Math.Log(2.1)) );
            Console.WriteLine("2.1**2.1 * 2.1**(-2.1) = Exp(2.1*Log(2.1)) * Exp(-2.1*Log(2.1)) = "  + Math.Exp(2.1*Math.Log(2.1)) * Math.Exp(-2.1*Math.Log(2.1)) );
            Console.WriteLine();


            int k = 301;
            x = -1.029;
            double t1 = nPow(x, k);
            double t2 = gPow(x, k);
            double t3 = mPow(x, k);
            Console.WriteLine("t1 = nPow(" + x + ", " + k + ") = " + t1 );
            Console.WriteLine("t2 = gPow(" + x + ", " + k + ") = " + t2 );
            Console.WriteLine("t3 = mPow(" + x + ", " + k + ") = " + t3 );
            Console.WriteLine("t1 / t2 = " + (t1 / t2) );
            Console.WriteLine("t1 - t2 = " + (t1 - t2) );
            Console.WriteLine("t1 == t2 ? " + ((t1 == t2) ? "yes" : "no") );
            Console.WriteLine("t1 / t3 = " + (t1 / t3) );
            Console.WriteLine("t1 - t3 = " + (t1 - t3) );
            Console.WriteLine("t1 == t3 ? " + ((t1 == t3) ? "yes" : "no") );
            Console.WriteLine("t2 / t3 = " + (t2 / t3) );
            Console.WriteLine("t2 - t3 = " + (t2 - t3) );
            Console.WriteLine("t2 == t3 ? " + ((t2 == t3) ? "yes" : "no") );
            Console.WriteLine();

            Console.WriteLine("Done.");
        }
    }
}

/*
Output:
[ Testing heronSqrt(double) ]--------------------
x = 16
u = Sqrt(16) = 4
y = heronSqrt(16) = 4
y*y = 16

[ Testing newtonCbrt(double) ]--------------------
x = -216
-Exp(Log(-x)/3.0) = -6
w = newtonCbrt(-216) = -6
w*w*w = -216

x = 729000000000
Exp(Log(x)/3.0) = 9000
w = newtonCbrt(729000000000) = 9000
w*w*w = 729000000000

[ Testing newtonNthRoot(int, double) ]--------------------
x = 729000000000
z = newtonNthRoot(3, 729000000000) = 9000
z*z*z = 729000000000

x = 1.296E+19
z = newtonNthRoot(4, x) = newtonNthRoot(4, 1.296E+19) = 60000
z*z*z*z = 1.296E+19

x = 7.71604938271605E-20
Exp(Log(x)/4.0) = 1.66666666666667E-05
z = newtonNthRoot(4, x) = newtonNthRoot(4, 7.71604938271605E-20) = 1.66666666666
667E-05
z*z*z*z = 7.71604938271605E-20

[ Test Exception heronSqrt(double) ]--------------------
x = -4
Calculating heronSqrt(-4)
Cannot find the sqrt of a negative number.
Caught some exception in calculating heronSqrt(-4)

[ Test Exception in newtonCbrt(double) ]--------------------
x = -4
Calculating newtonCbrt(-4)
y = newtonCbrt(-4) = -1.5874010519682
y*y*y = -4

[ Test calculations by powering ]-----------------------------
x = 200
Exp(Log(x)/10.0) = 1.69864646463425
z = newtonNthRoot(10, x) = newtonNthRoot(10, 200) = 1.69864646463425
Pow(z, 10) = 200

x = 3001
Exp(Log(x)/99.0) = 1.08423618932588
z = newtonNthRoot(99, x) = newtonNthRoot(99, 3001) = 1.08423618932588
Pow(z, 99) = 3001

x = 3001
Exp(Log(x)/-99.0) = 0.922308266265993
z = newtonNthRoot(-99, x) = newtonNthRoot(-99, 3001) = 0.922308266265993
1.0/Pow(z, 99) = 3001.00000000001

2.1**2.1 = Pow(2.1, 2.1) = 4.74963809174224
2.1**(-2.1) = Pow(2.1, -2.1) = 0.210542357266885
2.1**2.1 * 2.1**(-2.1) = Pow(2.1, 2.1) * Pow(2.1, -2.1) = 1
2.1**2.1 = Exp(2.1*Log(2.1)) = 4.74963809174224
2.1**(-2.1) = Exp(-2.1*Log(2.1)) = 0.210542357266885
2.1**2.1 * 2.1**(-2.1) = Exp(2.1*Log(2.1)) * Exp(-2.1*Log(2.1)) = 1

t1 = nPow(-1.029, 301) = -5457.92801577163
t2 = gPow(-1.029, 301) = -5457.92801577169
t3 = mPow(-1.029, 301) = -5457.92801577169
t1 / t2 = 0.999999999999989
t1 - t2 = 6.18456397205591E-11
t1 == t2 ? no
t1 / t3 = 0.999999999999989
t1 - t3 = 6.18456397205591E-11
t1 == t3 ? no
t2 / t3 = 1
t2 - t3 = 0
t2 == t3 ? yes

Done.
*/

 

 

 

Posted by Scripter
,

역삼각함수란 삼각함수의 역함수를 의미하고,

역쌍곡선함수란 쌍곡선함수의 역함수를 의미한다.

수학에서 sin 함수의 역함수는 arcsin 으로 표기되는데,

C# 언어에서는 Math.Asin 함수로 구현되어 있다.

아래의 소스는 Visual C# 으로 컴파일되는 소스이다.

/*
 * Filename: testArcSine.cs
 *
 * Compile: csc testArcSine.cs /reference:System.Numerics.dll
 * Execute: testArcSine
 *
 * Date: 2013. 1. 1.
 * Copyright (c) pkim _AT_ scripts.pe.kr
 */

using System;
using System.Numerics;

namespace ExperimentConsole
{
    class Program
    {
        public static double sin(double x)
        {
            double y = Math.Sin(x);
            return y;
        }

        public static double asin(double x)
        {
            double y = Math.Asin(x);
            return y;
        }

        public static double sinh(double x)
        {
            double y = Math.Sinh(x);
            return y;
        }

        public static double cosh(double x)
        {
            double y = Math.Cosh(x);
            return y;
        }

        public static double asinh(double x)
        {
            double y = Math.Log(x + Math.Sqrt(x*x + 1));
            return y;
        }

        public static double acosh(double x)
        {
            double y = Math.Log(x + Math.Sqrt(x*x - 1));
            return y;
        }

        public static void Main(string[] args)
        {
            double x = -0.9;
            double y = asin(x);
            Console.WriteLine("y = asin({0}) = {1:F9}", x,  y);
            Console.WriteLine("sin(y) = sin({0:F9}) = {1}",  y, sin(y));
            Console.WriteLine();

            x = 1.1;
            double u = acosh(x);
            Console.WriteLine("u = acosh({0}) = {1:F10}", x,  u);

            double v = asinh(x);
            Console.WriteLine("v = asinh({0}) = {1:F10}", x,  v);

            Console.WriteLine("cosh(u) = cosh({0:F10}) = {1}", u,  cosh(u));
            Console.WriteLine("sinh(v) = sinh({0:F10}) = {1}", v,  sinh(v));
        }
    }
}

/*
Output:
y = asin(-0.9) = -1.119769515
sin(y) = sin(-1.119769515) = -0.9

u = acosh(1.1) = 0.4435682544
v = asinh(1.1) = 0.9503469298
cosh(u) = cosh(0.4435682544) = 1.1
sinh(v) = sinh(0.9503469298) = 1.1
*/

 

 

Posted by Scripter
,

CodeBehind = ASP.NET 처음부터 있던 것. 이는 실행되기 이전에 먼저 컴파일되어야 하며, 컴파일되면 *.dll 파일은 bin 폴더에 생성된다. 배포(deploy)하기 전에 반드시 먼저 Visual Studio에서 컴파일되어야 한다. 고객에게 소스를 제공하고 싶지 않을 때는 CodeBehind을 사용한다. 배포할 때는 *.aspx 파일과 *.dll 파일, Web.config 파일 등(*.aspx.cs 파일과 *.aspx.vb 파일은 제외)만 제공하면 된다.

CodeFile = ASP.NET 2.0 부터 등장한 것. 개발한 것을 배포할 때는 소스 파일(*.aspx.vb 또는 *.aspx.cs 파일)도 함께 (*.dll 파일은 불포함) 제공해야 한다. ASP.NET 2.0 런타임이 필요시 마다 스스로 알아서 컴파일하며, 컴파일된 *.*.dll 파일은 C:\윈도우즈폴더\Microsfot.NET[.NET version]\Temporary ASP.NET Files 에 생성된다. (예: C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files )

 

* 비주얼 스튜디오(Visual Studio)에서 새로 작성할 때, 메뉴에서

         "새로 만들기(N)" -->"웹 사이트(W)..." --> "ASP.NET 웹 사이트" 

하면 생성된 *.aspx 파일이 CodeFile="..." 선언으로 작성되어 있고,

       "새로 만들기(N)" --> "프로젝트(P)..." -->  --> "ASP.NET 웹 응 용프로그램"

하면 생성된 *.aspx 파일이 CodeBehind="......" 선언으로 작성되어 있다.

개발을 시작할 때 웹사이트(WebSite)로 하였더라도, 차후에 모든 CodeFile="...." 선언을 CodeBehind="...." 선언으로 바꾸어 주고, 클래스 선언에 있던 partial 을 떼고, designer 파일에 있던 웹 컨트롤 선언(버튼 선언, 레이블 선언 등)들을 *.aspx.cs 파일(또는 *.aspx.vb 파일) 안으로 복사한 후 별도로 컴파일하면, 웹응용프로그램으로 바꾸어 배포할 수도 있다.

 

 

Posted by Scripter
,

근사 공식

         \frac{\pi}{\sqrt{12}} = \sum^\infty_{k=0} \frac{(-3)^{-k}}{2k+1}

을 이용하여 근사값 계산하는 프로그램을 C# 언어로 작성해 보았다.



/* * Filename: ApproximatePiOverSqrt12.cs * * Compile: csc ApproximatePiOverSqrt12.cs * Execute: ApproximatePiOverSqrt12 */ using System; public class ApproximatePiOverSqrt12 { /* Using the series: \frac{\pi}{\sqrt{12}} = \sum^\infty_{k=0} \frac{(-3)^{-k}}{2k+1} BND : 급수에서 합할 항의 개수 */ public static double Approximate(int BND) { int i; double sum = 0; double x; x = 1; sum = 1; for (i = 1; i <= BND; i++) { x = - (x / 3); sum = sum + x/(2*i + 1); } return sum; } public static void Main(string[] Args) { int BOUND = 100; double value1, value2, err; Console.WriteLine( "Approximate the value of PI/sqrt(12)" ); Console.WriteLine( "-------------------------------------------" ); value1 = Math.PI / Math.Sqrt(12.0); Console.WriteLine( " Evaluated directly: " + value1 ); value2 = Approximate(BOUND); Console.WriteLine( "Estimated by series: " + value2 ); err = value2 - value1; Console.WriteLine( " Error: " + err ); } }


실행 결과:
Approximate the value of PI/sqrt(12)
-------------------------------------------
 Evaluated directly: 0.906899682117109
Estimated by series: 0.906899682117109
              Error: 2.22044604925031E-16


Posted by Scripter
,


1. Add.cs 파일

// File: Add.cs
namespace UtilityMethods
{
    public class AddClass
    {
        public static long Add(long i, long j)
        {
            return (i + j);
        }
    }
}




2. Mult.cs 파일

// File: Mult.cs
namespace UtilityMethods
{
    public class MultiplyClass
    {
        public static long Multiply(long x, long y)
        {
            return (x * y);
        }
    }
}




3. TestCode.cs 파일

using UtilityMethods;

class TestCode
{
    static void Main(string[] args)
    {
        System.Console.WriteLine("Calling methods from MathLibrary.DLL:");

        if (args.Length != 2)
        {
            System.Console.WriteLine("Usage: TestCode <num1> <num2>");
            return;
        }

        long num1 = long.Parse(args[0]);
        long num2 = long.Parse(args[1]);

        long sum = AddClass.Add(num1, num2);
        long product = MultiplyClass.Multiply(num1, num2);

        System.Console.WriteLine("{0} + {1} = {2}", num1, num2, sum);
        System.Console.WriteLine("{0} * {1} = {2}", num1, num2, product);
    }
}



4. dll 파일 만들기

    csc /target:library /out:MathLibrary.DLL Add.cs Mult.cs


5. 테스트 실행 파일 만들기

csc /out:TestCode.exe /reference:MathLibrary.DLL TestCode.cs


6. 실행하기

  TestCode 1234 5678



Posted by Scripter
,

1. 다운로드
    http://www.alglib.net/ 에서 C#용 라이브러리 소스를 다운로드한다.


2. 다운로드한 파일의 압축을 적당한 디렉토리에 푼다.


3. 그 디렉토리로 가서 빌드한다. (옵션은 csc 와 mono 중에 택 1)
    build csc

    (빌드가 끝나면 out 디렉토리에 libalglib.dll 파일이 생성되어 있을 것이다.)


4. 빌드 후 테스트  (옵션은 csc 와 mono 중에 택 1)
   check csc all


5. 개별 테스트 (옵션 /reference 를 이용하여 dll 파일을 지정한다.)

   cd examples

   csc _demo_rcond_1.cs /reference:..\out\libalglib.dll
   _demo_rcond_1

   csc _demo_ode_example1.cs /reference:..\out\libalglib.dll
   _demo_ode_example1

   csc _demo_ode_example2.cs /reference:..\out\libalglib.dll
   _demo_ode_example2


Posted by Scripter
,


[파일명:  TestStringFindInList.cs]------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;

namespace MyTestApplication1 {

    class TestStringFindInList {

        public static void Main(String[] args) {
            List<string> words = new List<string>(new String[] { "하나", "둘", "셋", "넷", "다섯", "여섯" });
            int where;

            Console.Write("list: ");
            PrintArray(words);
            where = Find(words, "셋");
            if (where > 0) {
                Console.Write("발견!  ");
                Console.WriteLine("Next word of 셋 in list: " + words[where+1]);
            }

            Console.WriteLine("Sorting...");
            words.Sort();

            Console.Write("list: ");
            PrintArray(words);
            where = Find(words, "셋");
            if (where > 0) {
                Console.Write("발견!  ");
                Console.WriteLine("Next word of 셋 in list: " + words[where+1]);
            }
        }

        public static int Find(List<string> arr, String s) {
            for (int i = 0; i < arr.Count; i++) {
                if (arr[i].IndexOf(s) >= 0)
                    return i;
            }
            return -1;
        }

        public static void PrintArray(List<string> arr) {
            Console.Write("[");
            for (int i = 0; i < arr.Count - 1; i++) {
                Console.Write("{0}, ", arr[i]);
            }
            if (arr.Count > 0)
                Console.Write("{0}", arr[arr.Count - 1]);
            Console.WriteLine("]");
        }
    }
}
------------------------------------------------


컴파일> csc testStringFindInList.cs

실행> TestStringFindInList
list: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in list: 넷
Sorting...
list: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in list: 여섯


Posted by Scripter
,


[파일명:  TestStringFindApp.cs]------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;

namespace MyTestApplication1 {

    class TestStringFindApp {

        public static void Main(String[] args) {
            String[] words = new String[] { "하나", "둘", "셋", "넷", "다섯", "여섯" };
            int where;

            Console.Write("array: ");
            PrintArray(words);
            where = Find(words, "셋");
            if (where >= 0) {
                Console.Write("발견!  ");
                Console.WriteLine("Next word of 셋 in array: " + words[where+1]);
            }

            Console.WriteLine("Sorting...");
            Array.Sort(words);

            Console.Write("array: ");
            PrintArray(words);
            where = Find(words, "셋");
            if (where >= 0) {
                Console.Write("발견!  ");
                Console.WriteLine("Next word of 셋 in array: " + words[where+1]);
            }
        }

        public static int Find(String[] arr, String s) {
            for (int i = 0; i < arr.Length; i++) {
                if (arr[i].IndexOf(s) >= 0)
                    return i;
            }
            return -1;
        }

        public static void PrintArray(Object[] arr) {
            Console.Write("[");
            for (int i = 0; i < arr.Length - 1; i++) {
                Console.Write("{0}, ", arr[i]);
            }
            if (arr.Length > 0)
                Console.Write("{0}", arr[arr.Length - 1]);
            Console.WriteLine("]");
        }
    }
}
------------------------------------------------


컴파일> csc testStringFindApp.cs

실행> TestStringFindApp
array: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in array: 넷
Sorting...
array: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in array: 여섯



크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,

[파일명:  TestSortApp.cs]------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;

namespace MyTestApplication1 {

    class TestSortApp {

        public static void Main(String[] args) {
            String[] arr = new String[args.Length];
            for (int i = 0; i < args.Length; i++) {
                arr[i] = args[i];
            }
            Array.Sort(arr);
            PrintArray(arr);
        }

        public static void PrintArray(Object[] arr) {
            Console.Write("[");
            for (int i = 0; i < arr.Length - 1; i++) {
                Console.Write("{0}, ", arr[i]);
            }
            if (arr.Length > 0)
                Console.Write("{0}", arr[arr.Length - 1]);
            Console.WriteLine("]");
        }
    }
}
------------------------------------------------


컴파일> csc TestSortApp.cs

실행> TestSortApp one two three four five
[five, four, one, three, two]

실행> TestSortApp 하나 둘 셋 넷 다섯
[넷, 다섯, 둘, 셋, 하나]


 

크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,