JetBrasins 사의 인텔리제이 IDE 는 매우 유명한 자바 IDE 중 하나이다.

상용과 커뮤니티 용이 있는데 인텔리제이 IDE 내려받기에서 내려받으면 된다.

IDEA 를 처음 실행할 때 Java 홈 디렉토리와 Groovy 홈 디렉토리를 지정하고,

IDEA 창에서는 약간의 아이콘 메뉴를 지정한다.

새 Project 를 생성하고 src 폴더에 Groovy 클래스 GroovyHello 를 생성하여 아래와 같이 작성한다.

(Java 소스와 거의 유사한 Groovy 소스이다.)

윈도우즈의 파일 인코딩이 MS949 라 하더라도 IDEA 는 UTF-8 이 디폴트 인코딩이다.

Build 메뉴에서 빌드한 후, Run 메뉴에서 실행한다.

 

빌드하여 생성된 GroovyHello.class 를 명령창에서 java 커맨드로 직접 실행하려면 -cp 옵션으로 jar 라이브러리가 있는 곳을 지정해주면 된다.

프롬프트> java -cp .;C:\Groovy221\embeddable\groovy-all-2.2.1.jar GroovyHello
안녕? 나는 Groovy 입니다.
나는 Intelligent IDEA 도구를 이용하여 작성되었습니다.

 

Posted by Scripter
,

 

Groovy 언어 소스:

// Filename: testHexView_03.groovy
//
// Execute: groovy testHexView_03.groovy [filename]
//
// Date: 2013. 7. 28.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class TestHexView_03 {

    public static void printUsage() {
        System.out.println("groovy testHexView_03.groovy [filename]");
    }

    public static String toHex(byte b) {
        String s = "";
        int x1, x2;
        x1 = (b & 0xF0) >> 4;
        x2 = b & 0x0F;
        if (x1 < 10)
            s += (char)(x1 + (byte)'0');
        else
            s += (char)((x1 - 10) + (byte)'A');
        if (x2 < 10)
            s += (char)(x2 + (byte)'0');
        else
            s += (char)((x2 - 10) + (byte)'A');
        return s;
    }

    public static String toHex8(int n) {
        String s = "";
        int x1, x2, x3, x4, x5, x6, x7, x8;
        x1 = (n & 0xF0000000) >> 28;
        x2 = (n & 0xF000000) >> 24;
        x3 = (n & 0xF00000) >> 20;
        x4 = (n & 0xF0000) >> 16;
        x5 = (n & 0xF000) >> 12;
        x6 = (n & 0xF00) >> 8;
        x7 = (n & 0xF0) >> 4;
        x8 = n & 0x0F;
        if (x1 < 10)
            s += (char)(x1 + (byte)'0');
        else
            s += (char)((x1 - 10) + (byte)'A');
        if (x2 < 10)
            s += (char)(x2 + (byte)'0');
        else
            s += (char)((x2 - 10) + (byte)'A');
        if (x3 < 10)
            s += (char)(x3 + (byte)'0');
        else
            s += (char)((x3 - 10) + (byte)'A');
        if (x4 < 10)
            s += (char)(x4 + (byte)'0');
        else
            s += (char)((x4 - 10) + (byte)'A');
        s += " ";
        if (x5 < 10)
            s += (char)(x5 + (byte)'0');
        else
            s += (char)((x5 - 10) + (byte)'A');
        if (x6 < 10)
            s += (char)(x6 + (byte)'0');
        else
            s += (char)((x6 - 10) + (byte)'A');
        if (x7 < 10)
            s += (char)(x7 + (byte)'0');
        else
            s += (char)((x7 - 10) + (byte)'A');
        if (x8 < 10)
            s += (char)(x8 + (byte)'0');
        else
            s += (char)((x8 - 10) + (byte)'A');
  
        return s;
    }

    public static void main(String[] args) {

        if (args.length < 1) {
            printUsage();
            System.exit(1);
        }
     
        String filename = args[0];

        try {

            File infile = new File(filename);
            if  (!infile.exists()) {
                 System.out.println("The file \"" + filename + "\" does not exist.");
                 System.exit(1);
            }

            if (!infile.canRead()) {
                 System.out.println("The file \"" + filename + "\" is not allowed to be read.");
                 System.exit(1);
            }   

            if  (infile.isDirectory()) {
                 System.out.println("The file \"" + filename + "\" is a directory.");
                 System.exit(1);
            }

            FileInputStream fileInput = new FileInputStream(infile);

            long fileSize = new File(args[0]).length();
            if  (fileSize < 1L) {
                 System.out.println("The file size is zero.");
                 System.exit(1);
            }

            System.out.println("The size of the file \"" + filename + "\" is " + fileSize + ".\n");
             
            long n = 0L;

            int data;
            String dum = "";

            while (n < fileSize && (data = fileInput.read()) != -1) {
                if (n % 16 == 0L) {
                    System.out.print(toHex8((int) (n & 0xFFFFFFFF)) + ": ");
                }
             
                if (n % 16 != 8L) {
                    System.out.print(" ");
                }
                else {
                    System.out.print("-");
                }
                System.out.print( toHex((byte) (data & 0xFF)) );
                
                if ((data & 0xFF) >= 0x20 && (data & 0xFF) <= 0x7E) {
                    dum += (char)  (data & 0xFF);
                }
                else {
                    dum += ".";
                }
                
                if (n > 0 && n % 16 == 15L) {
                    System.out.print("  |");
                    System.out.print(dum);
                    System.out.print("|");
                    System.out.println();
                    dum = "";
                }
             
                n++;
            }

            if (n > 0 && n % 16 > 0) {
                for (int i = (int)(n % 16); i < 16; i++) {
                    System.out.print("   ");
                }
                System.out.print("  |");
                System.out.print(dum);
                for (int i = (int)(n % 16); i < 16; i++) {
                    System.out.print(" ");
                }
                System.out.print("|");
                System.out.println();
                dum = "";
            }

            fileInput.close();

            System.out.println();
            System.out.println("Read " + n + " bytes.");
        }
        catch (IOException e) {
            System.out.println("Error message: " + e.getMessage());
        }   
    }

}

 

 

실행 예 1> groovy testHexView_03.groovy temp_1.bin
The size of the file "temp_1.bin" is 12.

0000 0000:  48 65 6C 6C 6F 20 74 68-65 72 65 0A              |Hello there.    |

Read 12 bytes.

 

실행 예 2> groovy testHexView_03.groovy myFile.ser
The size of the file "myFile.ser" is 130.

0000 0000:  AC ED 00 05 73 72 00 06-50 65 72 73 6F 6E 07 31  |....sr..Person.1|
0000 0010:  46 DB A5 1D 44 AB 02 00-03 49 00 03 61 67 65 4C  |F...D....I..ageL|
0000 0020:  00 09 66 69 72 73 74 4E-61 6D 65 74 00 12 4C 6A  |..firstNamet..Lj|
0000 0030:  61 76 61 2F 6C 61 6E 67-2F 53 74 72 69 6E 67 3B  |ava/lang/String;|
0000 0040:  4C 00 08 6C 61 73 74 4E-61 6D 65 71 00 7E 00 01  |L..lastNameq.~..|
0000 0050:  78 70 00 00 00 13 74 00-05 4A 61 6D 65 73 74 00  |xp....t..Jamest.|
0000 0060:  04 52 79 61 6E 73 71 00-7E 00 00 00 00 00 1E 74  |.Ryansq.~......t|
0000 0070:  00 07 4F 62 69 2D 77 61-6E 74 00 06 4B 65 6E 6F  |..Obi-want..Keno|
0000 0080:  62 69                                            |bi              |

Read 130 bytes.

 

 

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 + 1/(x**(n - 1))) / n    를 이용

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

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

 

Groovy 언어로는 Java 언어 처럼 java.lang 패키지의 지수 연산 함수 Math.pow(밑수, 지수) 를 사용하면 된다. 아니면 Python 언어 처럼 (밑수)**(지수) 의 형식의 구문을 사용해도 된다. 하지만 차후 필요한 데가 있을 것 같아서 이와 유사한 n 제곱 함수와 n 제곱근 함수를 구현해 보았다.

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

아래의 소스는 대부분 버전의 Groovy 에서 실행되도록 작성된 소스이다.

Groovy 언어는 내부적으로 수치를 다룰 때 int 타입과 BigInteger 타입 간에 그리고 double 타입과 BigDecimal 타입 간에 자동으로 변환시키기 때문에 수치 리터럴을 파싱하고 수치를 출력하는데 Java 와 다를 수 있다. 예를 들어, 아래의 소스 중에서

//---------------------------
/// x = 1.0/12960000000000000000.0            //  Groovy fails to parse this. Is It a bug of Groovy?
x = 1.0/(12960000000000000000.0).toDouble()     // Okay!! This should work in Groovy.
z = newtonNthRoot(4, x)

로 작성된 부분은 Groovy 가  수치 리터럴 12960000000000000000.0 은 제대로 파싱하면서 그 역수 1.0/12960000000000000000.0 은 0,0 으로 인식하는 문제가 잇어 BigDecimal 을 명시적으로 double 타입으로 타입변환하는 부분 (수치).toDouble() 을 추가하여

x = 1.0/(12960000000000000000.0).toDouble()

로 작성하게 되었다.

 

/*
 * Filename: testNthRoot.groovy
 *
 *            Approximate square roots, cubic roots and n-th roots of a given number.
 *
 * Execute: groovy testNthRoot.groovy
 *
 * Date: 2013. 1. 7.
 * Copyright (c) 2013 PH Kim  (pkim __AT__ scripts.pe.kr)
 */
 
MAX_ITER = 20000
M_EPSILON = 1.0e-15

//
// Compute the n-th root of x to a given scale, x > 0.
//
def 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 {
                def y = 1.0
                for (i in 0..<n) {
                    y *= a
                }
                return y
            }
        }
    }
    else if (n == 0)
        return 1.0
    else {      //  when n < 0
        if (a == 0.0)
            throw new RuntimeException("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.
//
def 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 {
                def y = 1.0
                def r = a
                def m = 8*4 - 1           //  8*sizeof(int) - 1;
                def one = 1
                for (i in 0..m) {
                    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 RuntimeException("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.
//
def 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 {
                def y = 1.0
                def r = a
                def 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 RuntimeException("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.
//
def heronSqrt(double a) {
    if (a < 0.0)
        throw new RuntimeException("Cannot find the sqrt of a negative number.");
    else if (a == 0.0 || a == 1.0)
        return a
    else {
        def x1 = a
        def x2 = (x1 + a/x1)/2.0
        def er = x1 - x2
        def 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 += 1
            if (counter > MAX_ITER)
                break
        }
        if (counter >= MAX_ITER)
            throw new RuntimeException("Inaccurate sqrt exception by too many iterations.");
        return x2
    }
}


//
// Compute the cubic root of x to a given scale, x > 0.
//
def newtonCbrt(double a) {
    if (a == 0.0 || a == 1.0 || a == -1.0)
        return a
    else if (a < 0.0) {
        return -newtonCbrt(-a)
    }
    else {
        def x1 = a
        def x2 = (2.0*x1 + a/(x1*x1))/3.0
        def er = x1 - x2
        def 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 += 1
            if (counter > MAX_ITER)
                break
        }
        if (counter >= MAX_ITER)
            throw new RuntimeException("Inaccurate cbrt exception by too many iterations.");
        return x2
    }
}


//
// Compute the n-th root of x to a given scale, x > 0.
//
def 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 RuntimeException("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 RuntimeException("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 {
            def x1 = a
            def xn = mPow(x1, n - 1)
            def x2 = ((n - 1)*x1 + a/xn)/n
            def er = x1 - x2
            def 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 += 1
                if (counter > MAX_ITER)
                    break
            }
            if (counter >= MAX_ITER)
                throw new RuntimeException("Inaccurate n-th root exception by too many iterations.");
            return x2
        }
    }
    else {
        if (a == 0.0)
            throw new RuntimeException("Cannot find the negative n-th root of zero.");
        else
            return 1.0/newtonNthRoot(-n, a)
    }
}

 

x = 16.0
u = Math.sqrt(x)

print "[ Testing heronSqrt(double) ]--------------------\n"
printf("x = %g\n", x)
printf("u = sqrt(%g) = %g\n", x, u)
y = heronSqrt(x)
printf("y = heronSqrt(%g) = %g\n", x, y)
printf("y*y = %g\n", y*y)
print "\n"

print "[ Testing newtonCbrt(double) ]--------------------\n"
x = -216.0
printf("x = %g\n", x)
printf("-exp(log(-x)/3.0) = %g\n", -Math.exp(Math.log(-x)/3.0))
w = newtonCbrt(x)
printf("w = newtonCbrt(%g) = %g\n", x, w)
printf("w*w*w = %g\n", w*w*w)
print "\n"

x = 729000000000.0
printf("x = %g\n", x)
printf("exp(log(x)/3.0) = %g\n", Math.exp(Math.log(x)/3.0))
def w = newtonCbrt(x)
printf("w = newtonCbrt(%g) = %g\n", x, w)
printf("w*w*w = %g\n", w*w*w)
print "\n"

print "[ Testing newtonNthRoot(int, double) ]--------------------\n"
def z = newtonNthRoot(3, x)
printf("x = %g\n", x)
printf("z = newtonNthRoot(3, %g) = %g\n", x, z)
printf("z*z*z = %g\n", z*z*z)
print "\n"

x = 12960000000000000000.0
z = newtonNthRoot(4, x)
printf("x = %g\n", x)
printf("z = newtonNthRoot(4, x) = newtonNthRoot(4, %g) =  %g\n", x, z)
printf("z*z*z*z = %g\n", z*z*z*z)
print "\n"

//---------------------------
/// x = 1.0/12960000000000000000.0     // Groovy fails to parse this. Is It a bug of Groovy?
x = 1.0/(12960000000000000000.0).toDouble()   // Okay!! This should work in Groovy.
z = newtonNthRoot(4, x)
printf("x = %g\n", x)
printf("exp(log(x)/4.0) = %g\n", Math.exp(Math.log(x)/4.0))
printf("z = newtonNthRoot(4, x) = newtonNthRoot(4, %g) =  %g\n", x, z)
printf("z*z*z*z = %g\n", z*z*z*z)
print "\n"


try {
    x = -4.0
    print "[ Test Exception heronSqrt(double) ]--------------------\n"
    printf("x = %g\n", x)
    printf("Calculating heronSqrt(%g)\n", x)
    y = heronSqrt(x)
    printf("y = heronSqrt(%g) = %g\n", x, y)
    printf("y*y = %g\n", y*y)
    print "\n"
}
catch (RuntimeException ex) {
    printf("%s\nCaught some exception in calculating heronSqrt(%g)\n", ex.getMessage(), x)
    print "\n"
}


try {
    x = -4.0
    print "[ Test Exception in newtonCbrt(double) ]--------------------\n"
    printf("x = %g\n", x)
    printf("Calculating newtonCbrt(%g)\n", x)
    y = newtonCbrt(x)
    printf("y = newtonCbrt(%g) = %g\n", x, y)
    printf("y*y*y = %g\n", y*y*y)
    print "\n"
}
catch (RuntimeException ex) {
    printf("%s\nCaught some exception in calculating newtonCbrt(%g)\n", ex.getMessage(), x)
    print "\n"
}


print "[ Test calculations by powering ]-----------------------------\n"
x = 200.0
z = newtonNthRoot(10, x)
printf("x = %g\n", x)
printf("exp(log(x)/10.0) = %g\n", Math.exp(Math.log(x)/10.0))
printf("z = newtonNthRoot(10, x) = newtonNthRoot(10, %g) = %g\n", x, z)
printf("z**10 = pow(z, 10) = %g\n", z**10)
print "\n"

x = 3001.0
z = newtonNthRoot(99, x)
printf("x = %g\n", x)
printf("exp(log(x)/99.0) = %g\n", Math.exp(Math.log(x)/99.0))
printf("z = newtonNthRoot(99, x) = newtonNthRoot(99, %g) = %g\n", x, z)
printf("z**99 = pow(z, 99) = %g\n", z**99)
print "\n"

x = 3001.0
z = newtonNthRoot(-99, x)
printf("x = %g\n", x)
printf("exp(log(x)/-99.0) = %g\n", Math.exp(Math.log(x)/-99.0))
printf("z = newtonNthRoot(-99, x) = newtonNthRoot(-99, %g) = %g\n", x, z)
printf("1.0/z**99 = 1.0/pow(z, 99) = %g\n", 1.0/z**99)
print "\n"

printf("2.1**2.1 = pow(2.1, 2.1) = %g\n", 2.1**2.1)
printf("2.1**(-2.1) = pow(2.1, -2.1) = %g\n", 2.1**(-2.1))
printf("2.1**2.1 * 2.1**(-2.1) = pow(2.1, 2.1) * pow(2.1, -2.1) = %g\n", ((2.1** 2.1)*2.1**( -2.1)))
printf("2.1**2.1 = exp(2.1*log(2.1)) = %g\n", Math.exp(2.1*Math.log(2.1)))
printf("2.1**(-2.1) = exp(-2.1*log(2.1)) = %g\n", Math.exp(-2.1*Math.log(2.1)))
printf("2.1**2.1 * 2.1**(-2.1) = exp(2.1*log(2.1)) * exp(-2.1*log(2.1)) = %g\n", (Math.exp(2.1*Math.log(2.1)) * Math.exp(-2.1*Math.log(2.1))))
print "\n"


k = 301
x = -1.029
t1 = nPow(x, k)
t2 = gPow(x, k)
t3 = mPow(x, k)
printf("%g**%d = %g\n", x, k,  x**k )   // pow(x, k)
printf("t1 = nPow(%g, %d) = %g\n", x, k,  t1)
printf("t2 = gPow(%g, %d) = %g\n", x, k,  t2)
printf("t3 = mPow(%g, %d) = %g\n", x, k,  t3)
printf("t1 / t2 = %g\n", t1 / t2)
printf("t1 - t2 = %g\n", t1 - t2)
print "t1 == t2 ? "
if (t1 == t2)
    print "yes\n"
else
   print "no\n"
printf("t1 / t3 = %g\n", t1 / t3)
printf("t1 - t3 = %g\n", t1 - t3)
print "t1 == t3 ? "
if (t1 == t2)
    print "yes\n"
else
   print "no\n"
printf("t1 / t3 = %g\n", t1 / t3)
printf("t1 - t3 = %g\n", t1 - t3)
print "t1 == t3 ? "
if (t1 == t3)
    print "yes\n"
else
   print "no\n"
printf("t2 / t3 = %g\n", t2 / t3)
printf("t2 - t3 = %g\n", t2 - t3)
print "t2 == t3 ? "
if (t2 == t2)
    print "yes\n"
else
   print "no\n"
print "\n"


print "Done.\n"

 

/*
Output:
[ Testing heronSqrt(double) ]--------------------
x = 16.0000
u = sqrt(16.0000) = 4.00000
y = heronSqrt(16.0000) = 4.00000
y*y = 16.0000

[ Testing newtonCbrt(double) ]--------------------
x = -216.000
-exp(log(-x)/3.0) = -6.00000
w = newtonCbrt(-216.000) = -6.00000
w*w*w = -216.000

x = 7.29000e+11
exp(log(x)/3.0) = 9000.00
w = newtonCbrt(7.29000e+11) = 9000.00
w*w*w = 7.29000e+11

[ Testing newtonNthRoot(int, double) ]--------------------
x = 7.29000e+11
z = newtonNthRoot(3, 7.29000e+11) = 9000.00
z*z*z = 7.29000e+11

x = 1.29600e+19
z = newtonNthRoot(4, x) = newtonNthRoot(4, 1.29600e+19) =  60000.0
z*z*z*z = 1.29600e+19

x = 0.000000000000000000077160493827
x == 0.0 ? false
x = 7.71605e-20
exp(log(x)/4.0) = 1.66667e-05
z = newtonNthRoot(4, x) = newtonNthRoot(4, 7.71605e-20) =  1.66667e-05
z*z*z*z = 7.71605e-20

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

[ Test Exception in newtonCbrt(double) ]--------------------
x = -4.00000
Calculating newtonCbrt(-4.00000)
y = newtonCbrt(-4.00000) = -1.58740
y*y*y = -4.00000

[ Test calculations by powering ]-----------------------------
x = 200.000
exp(log(x)/10.0) = 1.69865
z = newtonNthRoot(10, x) = newtonNthRoot(10, 200.000) = 1.69865
z**10 = pow(z, 10) = 200.000

x = 3001.00
exp(log(x)/99.0) = 1.08424
z = newtonNthRoot(99, x) = newtonNthRoot(99, 3001.00) = 1.08424
z**99 = pow(z, 99) = 3001.00

x = 3001.00
exp(log(x)/-99.0) = 0.922308
z = newtonNthRoot(-99, x) = newtonNthRoot(-99, 3001.00) = 0.922308
1.0/z**99 = 1.0/pow(z, 99) = 3001.00

2.1**2.1 = pow(2.1, 2.1) = 4.74964
2.1**(-2.1) = pow(2.1, -2.1) = 0.210542
2.1**2.1 * 2.1**(-2.1) = pow(2.1, 2.1) * pow(2.1, -2.1) = 1.00000
2.1**2.1 = exp(2.1*log(2.1)) = 4.74964
2.1**(-2.1) = exp(-2.1*log(2.1)) = 0.210542
2.1**2.1 * 2.1**(-2.1) = exp(2.1*log(2.1)) * exp(-2.1*log(2.1)) = 1.00000

-1.02900**301 = -5457.93
t1 = nPow(-1.02900, 301) = -5457.93
t2 = gPow(-1.02900, 301) = -5457.93
t3 = mPow(-1.02900, 301) = -5457.93
t1 / t2 = 1.00000
t1 - t2 = 6.18456e-11
t1 == t2 ? no
t1 / t3 = 1.00000
t1 - t3 = 6.18456e-11
t1 == t3 ? no
t1 / t3 = 1.00000
t1 - t3 = 6.18456e-11
t1 == t3 ? no
t2 / t3 = 1.00000
t2 - t3 = 0.00000
t2 == t3 ? yes

Done.
*/

 

 

 

Posted by Scripter
,

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

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

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

Groovy 언어에서는 Java 의  java.lang.Math.asin(double) 메소드f를 사용한다.

/*
 * Filename: testArcSine.groovy
 *
 * Execute: goovy  testArcSine.groovy
 *
 * Date: 2013. 1. 2.
 * Copyright (c) pkim _AT_ scripts.pe.kr
 */

def sin(double x)  {
            double y = Math.sin(x)
            return y
}

def double asin(double x) {
            double y = Math.asin(x)
            return y
}

def sinh(double x) {
            double y = Math.sinh(x)
            return y
}

def cosh(double x) {
            double y = Math.cosh(x)
            return y
}

def asinh(double x) {
            double y = Math.log(x + Math.sqrt(x*x + 1))
            return y
}

def acosh(double x) {
            double y = Math.log(x + Math.sqrt(x*x - 1))
            return y
}

def x = -0.9
def y = asin(x)
printf("y = asin(%.1g) = %.9f\n", x,  y)
printf("sin(y) = sin(%.9f) = %.1g\n",  y, sin(y))
printf("\n")

x = 1.1
def u = acosh(x)
printf("u = acosh(%3.2g) = %.10f\n", x,  u)

def v = asinh(x)
printf("v = asinh(%3.2g) = %.10f\n", x,  v)

printf("cosh(u) = cosh(%.10f) = %3.2g\n", u,  cosh(u))
printf("sinh(v) = sinh(%.10f) = %3.2g\n", 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
,

Groovy 버전이 너무 높으면 나는 에러입니다.

이런 에러를 내지 않는 버전은 현재로서는 1.8.4 와 2.0.1 까지 입니다. 그 이후 버전에서는 *.groovy 로 인식되는 Groovlet 웹페이지를 재방문할 때 404 (Resource Not Found) 에러가 납니다.


* web.xml 파일에 추가할 내요

    <servlet>

        <servlet-name>SessionExample</servlet-name>

        <servlet-class>SessionExample</servlet-class>

    </servlet>


    <servlet>

        <servlet-name>Groovy</servlet-name>

        <servlet-class>groovy.servlet.GroovyServlet</servlet-class>

    </servlet>

    <servlet>

        <servlet-name>GTemplate</servlet-name>

        <servlet-class>groovy.servlet.TemplateServlet</servlet-class>

        <init-param>

         <param-name>groovy.source.encoding</param-name>

         <param-value>UTF-8</param-value>

        </init-param>

    </servlet>


    <servlet-mapping>

        <servlet-name>GTemplate</servlet-name>

        <url-pattern>*.ghtml</url-pattern>

    </servlet-mapping>

    <servlet-mapping>

        <servlet-name>GTemplate</servlet-name>

        <url-pattern>*.gsp</url-pattern>

    </servlet-mapping>

    <servlet-mapping>

        <servlet-name>Groovy</servlet-name>

        <url-pattern>*.groovy</url-pattern>

    </servlet-mapping>



[참고 자료]

  1. Jira 버그 리포트: https://jira.codehaus.org/browse/GROOVY-5747  8 Oct 2012 – First call to Groovlet succeeds but subsequent calls return 404...GroovyServlet Error: script: '/test.groovy': Script not found, sending 404
  2. 이전 버전 Groovy 다운로드: http://dist.codehaus.org/groovy/distributions/
  3. 최신 버전 Groovy 다운로드: http://groovy.codehaus.org/Download?nc
  4. Groovlet 동작 확인:

 

Posted by Scripter
,

2**2**5  은 (2**2)**5  와 2**(2**5) 중에 어느 것과 같을까?
즉, 지수 연산자 **는 왼쪽에서 오른쪽으로(left to right) 진행할까?
아니면 오른쪽에서 왼쪽으로(right to left) 진행할까?

만일 2**2**5 == (2**2)**5  라면 그 결과는 2**10 과 같을 것이고,
만일  2**2**5 == 2**(2**5)  라면 그 결과는 2**32 과 같을 것이다.

* 미리 결론을 말하면 Groovy 언어에서는 지수 계산의 순서가 다른 언어(Python. Ruby, Maxima 등)의 것과는 다르다는 것이다.


1. groovy 의 경우

groovysh 로 테스트하였다.

Groovy Shell (1.7.3, JVM: 1.6.0_17)
Type 'help' or '\h' for help.
-------------------------------------------------------------------------------
groovy:000> println(2**5)
32
===> null
groovy:000> println(5**2)
25
===> null
groovy:000> println(2**2**5)
1024
===> null
groovy:000> exit




2. python의 경우

python으로 테스트하였다.

Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print 2**5
32
>>> print 5**2
25
>>> print 2**2**5
4294967296




3. ruby 의 경우

irb로 테스트하였다.

irb(main):001:0> print "%d\n" % (2**5)
32
=> nil
irb(main):002:0> print "%d\n" % (5**2)
25
=> nil
irb(main):003:0> print "%d\n" % (2**2**5)
4294967296
=> nil
irb(main):004:0> exit




4. wxMaxima 의 경우

wxMaxima로 테스트하였다.




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,
Groovy 언어로 숫자 맞추기 게임을 작성해 보았다.
소스에서 눈여겨볼 부분은 15째~17째 줄이다.

    def r = new BufferedReader(new InputStreamReader(System.in))
    def sbuf = r.readLine()
    def guess = sbuf.toInteger()

Groovy 언어의 구문 바탕(syntax body)은 Java의 것을 빌려쓰고 있다.


소스 파일명: guessNumber01.groovy
  1. /*
  2.  *  Filename: guessNumber01.groovy
  3.  *  Purpose:  Interatice game guessing a given number.
  4.  *                if {CONDITION) {
  5.  *                    ......
  6.  *                }
  7.  *                else {
  8.  *                    ......
  9.  *                }
  10.  *  Execute: groovy guessNumber01.groovy
  11.  */
  12. def doGuessing(num) {
  13.     println("Enter your guess:")
  14.     def r = new BufferedReader(new InputStreamReader(System.in))
  15.     def sbuf = r.readLine()
  16.     def guess = sbuf.toInteger()
  17.     if (guess == num) {
  18.         println("You win!")
  19.         return
  20.     }
  21.     // we won't get here if guess == num
  22.     if (guess < num) {
  23.         println("Too low!")
  24.         doGuessing(num)
  25.     }
  26.     else {
  27.         println("Too high!")
  28.         doGuessing(num)
  29.     }
  30. }
  31. doGuessing(123)



실행> groovy guessNumber01.groovy
Enter your guess:
111
Too low!
Enter your guess:
222
Too high!
Enter your guess:
123
You win!




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.





Posted by Scripter
,


[파일명:  testStringFindInList.groovy]------------------------------------------------
def find(ArrayList<String> arr, String s) {
    for (int i = 0; i < arr.size(); i++) {
     if (arr.get(i).indexOf(s) >= 0)
      return i
    }
    return -1;
}

def printArray(ArrayList<String> arr) {
    print("[")
    for (int i = 0; i < arr.size() - 1; i++) {
         print(arr.get(i) + ", ")
    }
    if (arr.size() > 0)
        print(arr.get(arr.size() - 1))
    println("]")
}

ArrayList<String> words = ["하나", "둘", "셋", "넷", "다섯", "여섯"] as ArrayList<String>
int where

print("list: ")
printArray(words)
where = find(words, "셋")
if (where > 0) {
    print("발견!  ")
    println("Next word of 셋 in list: " + words.get(where+1))
}

println("Sorting...")
Collections.sort(words)

print("list: ")
printArray(words)
where = find(words, "셋")
if (where > 0) {
    print("발견!  ")
    println("Next word of 셋 in list: " + words.get(where+1))
}
------------------------------------------------


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


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

Posted by Scripter
,


[파일명:  testStringFindInVector.groovy]------------------------------------------------
def find(Vector<String> arr, String s) {
    for (int i = 0; i < arr.size(); i++) {
     if (arr.elementAt(i).indexOf(s) >= 0)
      return i;
    }
    return -1;
}

def printArray(Vector<String> arr) {
    print("[");
    for (int i = 0; i < arr.size() - 1; i++) {
         print(arr.elementAt(i) + ", ");
    }
    if (arr.size() > 0)
        print(arr.elementAt(arr.size() - 1));
    println("]");
}


String[] data = [ "하나", "둘", "셋", "넷", "다섯", "여섯" ] as String[]
Vector<String> words = new Vector<String>()
for (int i = 0; i < data.length; i++) {
    words.add(data[i])
}
int where

print("vector: ")
printArray(words)
where = find(words, "셋")
if (where > 0) {
    print("발견!  ")
    println("Next word of 셋 in vector: " + words.elementAt(where+1))
}

println("Sorting...")
Collections.sort(words)

print("vector: ")
printArray(words)
where = find(words, "셋")
if (where > 0) {
    print("발견!  ")
    println("Next word of 셋 in vector: " + words.elementAt(where+1))
}
------------------------------------------------


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


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

Posted by Scripter
,

우선 다음 소스는 Java용 소스를 //// 표시가 붙은 줄 한 줄만 수정하여 Groovy영 소스로 고친 것이다.

[파일명:  testStringFindApp.groovy]------------------------------------------------
import java.util.*;

public class TestStringFindApp {

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

        System.out.print("array: ");
        printArray(words);
        where = find(words, "셋");
        if (where > 0) {
            System.out.print("발견!  ");
            System.out.println("Next word of 셋 in array: " + words[where+1]);
        }

        System.out.println("Sorting...");
        Arrays.sort(words);

        System.out.print("array: ");
        printArray(words);
        where = find(words, "셋");
        if (where > 0) {
            System.out.print("발견!  ");
            System.out.println("Next word of 셋 in array: " + words[where+1]);
        }
    }

    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;
    }

    static void printArray(String[] arr) {
        System.out.print("[");
        for (int i = 0; i < arr.length - 1; i++) {
            System.out.print(arr[i] + ", ");
        }
        if ( arr.length > 0)
            System.out.print(arr[arr.length - 1]);
        System.out.println("]");
    }
}
------------------------------------------------


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



그리고 다음 소스는 위의 Groovy용 소스를 더 Grovy 소스 코드답게 짧게 만든 것이다.

[파일명:  testStringFindApp.groovy]------------------------------------------------
def find(String[] arr, String s) {
   for (int i = 0; i < arr.length; i++) {
     if (arr[i].indexOf(s) >= 0)
      return i;
    }
    return -1;
}

def printArray(String[] arr) {
    print("[");
    for (int i = 0; i < arr.length - 1; i++) {
        print(arr[i] + ", ");
    }
    if (arr.length > 0)
        print(arr[arr.length - 1]);
    println("]");
}

String[] words = [ "하나", "둘", "셋", "넷", "다섯", "여섯" ] as String[]
int where

print("array: ")
printArray(words)
where = find(words, "셋")
if (where > 0) {
    print("발견!  ")
    println("Next word of 셋 in array: " + words[where+1])
}

println("Sorting...")
Arrays.sort(words)

print("array: ")
printArray(words)
where = find(words, "셋")
if (where > 0) {
    print("발견!  ")
    println("Next word of 셋 in array: " + words[where+1])
}
------------------------------------------------


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


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

 


Posted by Scripter
,