Showing posts with label groovy. Show all posts
Showing posts with label groovy. Show all posts

Wednesday, March 11, 2015

Groovy closure to find Pi and sqrt(2)

I want to start with very simple math fact - if we draw right triangle and two of edges of this triangle have length equal to sqrt(2). Area of this triangle is of course 1 (because: 1/2*a*h).

Another fact is that area under function sin(x) from 0 to pi/2 is also equal to 1.

Let's use those facts to exploit groovy closures to estimate pi and sqrt(2).

Clone repo: git clone https://github.com/piotrpietrzak/gatchaman.git
git checkout origin/groovypi

We should start with tests - this time we will use spock with "where:" block.

def "should converge to square root of two"(scale, sumToLimit, expectedResult) {
    expect:
    new DefiniteIntegral()
            .compute(scale, sumToLimit , { it }) == expectedResult

    where:
    scale | sumToLimit | expectedResult
    1     | 1          | 1.4
    2     | 1          | 1.41
    3     | 1          | 1.414
    4     | 1          | 1.4142
    5     | 1          | 1.41421
    6     | 1          | 1.414214
}

For pi this is also very simple test:

def "should converge to pi"(scale, sumToLimit, expectedResult) {
    expect:
    new DefiniteIntegral()
            .compute(scale, sumToLimit, { Math.sin(it) }) * 2 == expectedResult

    where:
    scale | sumToLimit | expectedResult
    1     | 1          | 3.2    
    2     | 1          | 3.14
    3     | 1          | 3.142
    4     | 1          | 3.1416
    5     | 1          | 3.14160
    6     | 1          | 3.141592
}

Definite integral is quite simple (from the numerical recipes point of view we can achieve much better results even with this naive approach but I want to keep this simple).

while (sum < integrateTo) {
    x += step
    sum += function(x) * step
}

After this loop we should return x which is our result.

What else can we do better?

Every math lover will tell us other things but IT guys will focus on poor API and unnecessary method. Lets replace this simple solution with this:
class IntegrationClosure {
    final Closure<BigInteger> compute = {
        Integer scale, BigDecimal integrateTo, Closure<BigDecimal> function ->
            BigDecimal sum = 0;
            BigDecimal x = 0;
            BigDecimal step = BigDecimal.valueOf(1, scale)

            while (sum < integrateTo) {
                x += step
                sum += function(x) * step
            }
            x
    }
}


Sunday, March 8, 2015

Port conflicts during tests

When I was running tests in very large and sophisticated system I found very interesting problem. During integration tests run in parallel there was port conflicts and port collision prevents tests to run smoothly and in the end they failed. To avoid this behavior I suggested to use very simple solution. My colleagues confirm the need and implementation was done in very short time. Just before you read the solution - please reconsider situation on your own:
  • Tests runs on many JVMs
  • You don't want to share state between mentioned above JVMs
  • You don't want to manually change every test to enter code
The solution suggested was to use random port in range and repeat this until success. Really simple and it just works. 
From technical perspective please focus on this closure from tests:
Server server = new AvailablePortScanner(minPort, maxPort).tryToExecuteWithFreePort(new Closure<Server>(this) {
    @Override    public Server call(Object... args) {
        Integer freePort = (Integer) args[0];
        Server server = new Server(freePort);
        System.setProperty("port", freePort.toString());
        return server;
    }
});
Checkout on branch:
origin/groovy/closure_port_scanner
to play with it. Have fun

Saturday, March 7, 2015

Groovy overloaded operator

Groovy overloaded operator (bit shift on objects)

This example come from "Groovy Goodness Notebook".

Clone repo:
git clone https://github.com/piotrpietrzak/gatchaman.git
Switch to branch:
git checkout origin/groovy/multiple_overloaded_operator_methods
Test in spock is quite interesting:
def "should add operation for user" () {
    setup:
    Priviledge priviledge = new Priviledge()
    User user = new User(name: 'Test name')
    Operation operation = new Operation(name: 'Test operation')

    when:
    priviledge << user << operation

    then:
    priviledge.users.contains user
    priviledge.operations.contains operation
}