2014年5月9日 星期五

python3 高精度小數

python3 高精度小數

做數學運算需要用高精度的浮點數,可以使用decimal模組

>>> from decimal import *
>>> Decimal(1/3)Decimal('0.333333333333333314829616256247390992939472198486328125')
>>> Decimal( 5e-115)
Decimal('5.000000000000000253224511584642904700031198975255267803449800938244847
07054082960234923746081859400858021097772021778402792777070155705765691787462823
35047908242924101834562519900509625714227417248975325003782562360654965752209815
93257539786334869563372595928867119233244230552121178945412793837022036314010620
1171875E-115')

2014年5月7日 星期三

java iterators

Iterators

Q. What is an Iterable ?
A. Has a method that returns an Iterator.

public interface Iterable<Item>
{
    Iterator<Item> iterator();
}


Q. What is an Iterator ?
A. Has methods hasNext() and next().

public interface Iterator<Item>
{
    boolean hasNext();
    Item next();
    void remove();
}


Q. Why make data structures Iterable ?
A. Java supports elegant client code.

for (String s : stack){
    StdOut.println(s);
}







2014年5月6日 星期二

python3 multiprocessing: Server process

Python3

Server process
A manager object returned by Manager() controls a server process which holds Python objects and allows other processes to manipulate them using proxies.
A manager returned by Manager() will support types listdictNamespaceLockRLockSemaphoreBoundedSemaphore,ConditionEventBarrierQueueValue and Array. For example,
from multiprocessing import Process, Manager

def f(d, l):
    d[1] = '1'
    d['2'] = 2
    d[0.25] = None
    l.reverse()

if __name__ == '__main__':
    with Manager() as manager:
        d = manager.dict()
        l = manager.list(range(10))

        p = Process(target=f, args=(d, l))
        p.start()
        p.join()

        print(d)
        print(l)
will print
{0.25: None, 1: '1', '2': 2}
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Server process managers are more flexible than using shared memory objects because they can be made to support arbitrary object types. Also, a single manager can be shared by processes on different computers over a network. They are, however, slower than using shared memory.

ref: https://docs.python.org/3.4/library/multiprocessing.html

2014年5月5日 星期一

python3 用profiling測執行時間

Python 有內建 profiling 的工具,叫做 profile,可以透過命令列直接下參數使用:
1
python -m cProfile -s time MODULE.py ARGUMENTS
這樣會執行 MODULE 再將測量結果輸出到螢幕,時間依單一函式執行時間來排序。引用官網的例子,cProfile 的輸出格式如下:
1
2
3
4
5
6
7
8
     2706 function calls (2004 primitive calls) in 4.504 CPU seconds
 
Ordered by: standard name
 
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    2    0.006    0.003    0.953    0.477 pobject.py:75(save_objects)
 43/3    0.533    0.012    0.749    0.250 pobject.py:99(evaluate)
 ...