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)
 ...

2014年4月20日 星期日

Comparable vs Comparator in Java

Comparable 和 Comparator 的差別

轉錄自:http://www.programcreek.com/2011/12/examples-to-demonstrate-comparable-vs-comparator-in-java/

1. Comparable
Comparable is implemented by a class in order to be able to comparing object of itself with some other objects. The class itself must implement the interface in order to be able to compare its instance(s). The method required for implementation is compareTo().
簡單來說,就是可以有比較的性質。但是你如果要有多種的比較方式可能就要使用comparator
class HDTV implements Comparable<HDTV> {
 private int size;
 private String brand;
 
 public HDTV(int size, String brand) {
  this.size = size;
  this.brand = brand;
 }
 
 public int getSize() {
  return size;
 }
 
 public void setSize(int size) {
  this.size = size;
 }
 
 public String getBrand() {
  return brand;
 }
 
 public void setBrand(String brand) {
  this.brand = brand;
 }
 
 @Override
 public int compareTo(HDTV tv) {
 
  if (this.getSize() > tv.getSize())
   return 1;
  else if (this.getSize() < tv.getSize())
   return -1;
  else
   return 0;
 }
}
 
public class Main {
 public static void main(String[] args) {
  HDTV tv1 = new HDTV(55, "Samsung");
  HDTV tv2 = new HDTV(60, "Sony");
 
  if (tv1.compareTo(tv2) > 0) {
   System.out.println(tv1.getBrand() + " is better.");
  } else {
   System.out.println(tv2.getBrand() + " is better.");
  }
 }
}
Sony is better.

2. Comparator
Comparator is capable if comparing objects based on different attributes. e.g. 2 men can be compared based on `name` or `age` etc. (this can not be done using comparable. )
你可以使用object中不同的特性做比較,像是人的`name` or `age` 
The method required to implement is compare(). Now let’s use another way to compare those TV by size. The common use of Comparator is sorting. Both Collections and Arrays classes provide a sort method which use a Comparator.
在實作中,你需要有一個compare()的function,讓你的comparator有比較的準則。一個class可以有多種的比較方式,要個別實作compare()的部份的部份。
通常Comparator會被用在做sort 。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
 
class HDTV {
 private int size;
 private String brand;
 
 public HDTV(int size, String brand) {
  this.size = size;
  this.brand = brand;
 }
 
 public int getSize() {
  return size;
 }
 
 public void setSize(int size) {
  this.size = size;
 }
 
 public String getBrand() {
  return brand;
 }
 
 public void setBrand(String brand) {
  this.brand = brand;
 }
}
 
class SizeComparator implements Comparator<HDTV> {
 @Override
 public int compare(HDTV tv1, HDTV tv2) {
  int tv1Size = tv1.getSize();
  int tv2Size = tv2.getSize();
 
  if (tv1Size > tv2Size) {
   return 1;
  } else if (tv1Size < tv2Size) {
   return -1;
  } else {
   return 0;
  }
 }
}
 
public class Main {
 public static void main(String[] args) {
  HDTV tv1 = new HDTV(55, "Samsung");
  HDTV tv2 = new HDTV(60, "Sony");
  HDTV tv3 = new HDTV(42, "Panasonic");
 
  ArrayList<HDTV> al = new ArrayList<HDTV>();
  al.add(tv1);
  al.add(tv2);
  al.add(tv3);
 
  Collections.sort(al, new SizeComparator());
  for (HDTV a : al) {
   System.out.println(a.getBrand());
  }
 }
}
Output:
Panasonic
Samsung
Sony

2014年4月14日 星期一

轉錄: HOWTO - 常見語言的套件安裝 (Perl、Python、Ruby)

HOWTO - 常見語言的套件安裝 (Perl、Python、Ruby)

不同隻程式會使用到不同的版本和package
perl 可用 perlbrew
python 可用  virtualenv 管理

以下網址有詳細的說明:
常見語言的套件安裝_(Perl、Python、Ruby)



Python virtualenv:

easy_install 這個工具(由 setuptools 提供)來安裝 Virtualenv

01. Linux

如果不知道 easy_install 或還沒安裝 setuptools,在 Debian/Ubuntu 可以用下列指令安裝:
$ sudo apt-get install python-setuptools

在 Fedora/CentOS/Redhat/openSUSE,則可以使用:
$ su -
# yum install python-setuptools
安裝virtualenv
# easy_install virtualenv

02. 使用方法

I. 建立虛擬環境
請於命令列模式下輸入下列指令:
$ virtualenv [指定虛擬環境的名稱]
例如下列指令會建立名為 "ENV" 的虛擬環境:
$ virtualenv ENV
預設在建立虛擬環境時,會依賴系統環境中的 site packages,如果想完全不依賴系統的 packages,可以加上參數 --no-site-packages 來建立虛擬環境:
$ virtualenv --no-site-packages [指定虛擬環境的名稱]

II. 啟動虛擬環境

請先切換當前目錄至建立的虛擬環境中。前例中,建立名稱為 "ENV",則:
$ cd ENV
接著,啟動虛擬環境:
$ source bin/activate
然後就可以注意到,在 shell 提示字元的最前面多了虛擬環境的名稱提示:
(ENV) ...$
III. 退出虛擬環境
請於命令列模式下輸入下列指令:
$ deactivate
就可以回到系統原先的 Python 環境。
IV. 在虛擬環境安裝新的 Python 套件
Virtualenv 在安裝時會附帶 pip 這個 Python 的套件安裝工具,當虛擬環境被啟動時,由它安裝的 package 會出現在虛擬環境的資料夾中,用法是:
(ENV)...$ pip install [套件名稱]
如果系統也有安裝 pip,請特別注意是否已經啟動虛擬環境,否則套件會被安裝到系統中,而非虛擬環境裡。
V. 從程式中指定使用虛擬環境的函數庫
無法從 Shell 啟動虛擬環境的情況,像是使用 mod_python 或 mod_wsgi,這時可以在 Python 的程式中加上:
activate_this = '/path/to/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))

來使用安裝在虛擬環境中的 packages。








2014年3月11日 星期二

好用的統計作圖QtiPlot

Qtiplot--統作圖

wiki

QtiPlot 是一個跨平台的數據分析和科學可視化軟體。它的主要開發者是 Ion Vasilief。
QtiPlot 的界面與同類軟體OriginSigmaPlot[1] 類似。此類軟體大多是專利軟體,且價格昂貴,因此,很多人(尤其是大學生)常用QtiPlot 來替代其它同類軟體[2]。QtiPlot 可以用於製作二維和三維的數據圖表,並具有許多諸如曲線擬合這樣的數據分析功能。Plotting of 3D data can be rendered using OpenGLusing the Qwt3D libraries.
QtiPlot 屬於自由軟體,採用GNU 通用公共許可證(GPL)發布。針對微軟 Windows、某幾種Linux發行版以及Mac OS X平台,QtiPlot 同時提供編譯好的二進制文件。使用者須要付費才能下載和使用這些二進制版本文件(demo版現在可以免費下載,但只能使用很短的時間);但是,任何人都可以在GPL下自由地重新編譯和分發QtiPlot[3]。目前,在Linux平台和Windows平台,都有這樣的第三方分發者

ubuntu的使用者可以直接在「軟體中心安裝」
官網:http://soft.proindependent.com/qtiplot.html 
相關論壇:http://soft.proindependent.com/doc/manual-en/index.html