# Significant Figures using Python

Ch. 1, Problems 1, 2, and 3 - Data Reduction and Error Analysis for the Physical Sciences by Philip Bevington:

1. How many significant figures are there in the following numbers?
1. 976.45
2. 84,000
3. 0.0094
4. 301.07
5. 4.000
6. 10
7. 5280
8. 400
2. What is the most significant figure in each of the numbers? What is the least significant?
3. Rround off each of the numbers above to two significant digits.

Solution:

As always I prefer to write a piece of code to complete the exercises. Shown below is a python module that has implementations of the necessary functionality.

'''
Implementation of significant digits and associated concepts.
'''

import math

def isNumeric(x):

'''Checks to see if x represents a numeric value by converting
into unicode and utilizing the isnumeric() method.'''

# first convert the number into a string
strRep = str(x)

# first make a unicode version so we can ensure we're dealing with
# something that represents a numeric value:
uRep = unicode(strRep)
if ('.' in uRep) and all([x.isnumeric() for x in uRep.split('.')]):
return True # there's a decimal and everything to the right
# and left of it is numeric
else:
return uRep.isnumeric()

def mostSigDigit(x):

'''Returns the most significant digit in x.'''

assert isNumeric(x), 'x must be numeric!'

# number the digits:
enumeratedChars = list(enumerate(str(x)))

nonZeroChars = [x for x in enumeratedChars if (x[1] != '0') and (x[1] != '.')]
return nonZeroChars[0][1]

def leastSigDigit(x):

'''Returns the least significant significant digit in x.'''

assert isNumeric(x), 'x must be numeric!'

# number the digits:
enumeratedChars = list(enumerate(str(x)))

nonZeroChars = [x for x in enumeratedChars if (x[1] != '0') and (x[1] != '.')]
mostSignificantDigit = nonZeroChars[0]

leastSignificantDigit = None
if '.' in [x[1] for x in enumeratedChars]:
leastSignificantDigit = enumeratedChars[-1]
else:
leastSignificantDigit = nonZeroChars[-1]

# here we have a pair so just return the value:
return leastSignificantDigit[1]

def numSigDigits(x):

'''Returns the number of significant digits in x.'''

assert isNumeric(x), 'x must be numeric!'

# number the digits:
enumeratedChars = list(enumerate(str(x)))

nonZeroChars = [x for x in enumeratedChars if (x[1] != '0') and (x[1] != '.')]
mostSignificantDigit = nonZeroChars[0]

leastSignificantDigit = None
if '.' in [x[1] for x in enumeratedChars]:
leastSignificantDigit = enumeratedChars[-1]
else:
leastSignificantDigit = nonZeroChars[-1]

enumedSignificantDigits = [x for x in enumeratedChars[mostSignificantDigit[0]:leastSignificantDigit[0] + 1]]

numDigits = len(enumedSignificantDigits)
if '.' in [x[1] for x in enumeratedChars]:
numDigits -= 1

return numDigits

def round_sigfigs(num, sig_figs):

"""Round to specified number of sigfigs.

>>> round_sigfigs(0, sig_figs=4)
0
>>> int(round_sigfigs(12345, sig_figs=2))
12000
>>> int(round_sigfigs(-12345, sig_figs=2))
-12000
>>> int(round_sigfigs(1, sig_figs=2))
1
>>> '{0:.3}'.format(round_sigfigs(3.1415, sig_figs=2))
'3.1'
>>> '{0:.3}'.format(round_sigfigs(-3.1415, sig_figs=2))
'-3.1'
>>> '{0:.5}'.format(round_sigfigs(0.00098765, sig_figs=2))
'0.00099'
>>> '{0:.6}'.format(round_sigfigs(0.00098765, sig_figs=3))
'0.000988'
"""
assert isNumeric(num), 'x must be numeric!'

if num != 0:
return round(num, -int(math.floor(math.log10(abs(num))) - (sig_figs - 1)))
else:
return 0  # Can't take the log of 0

if __name__ == '__main__':

import decimal
numberList = ['976.45', '84000', '0.0094', '301.07', '4.000', '10', '5280', '400']

for eachNum in map(lambda x: decimal.Decimal(str(x)), numberList):

originalNumStr = str(eachNum)
nsdStr = ":".join(['numSigDigits', str(numSigDigits(eachNum))])
msdStr = ":".join(['mostSigDigit', str(mostSigDigit(eachNum))])
lsdStr = ":".join(['leastSigDigit', str(leastSigDigit(eachNum))])
roundedNumStr = ":".join(['rounded', str(round_sigfigs(eachNum, 2))])

resultStr = "; ".join([originalNumStr, nsdStr, msdStr, lsdStr, roundedNumStr])

print resultStr



When you run this you should get something like the following:

$python significant.py 976.45; numSigDigits:5; mostSigDigit:9; leastSigDigit:5; rounded:980.0 84000; numSigDigits:2; mostSigDigit:8; leastSigDigit:4; rounded:84000.0 0.0094; numSigDigits:1; mostSigDigit:9; leastSigDigit:4; rounded:0.0094 301.07; numSigDigits:5; mostSigDigit:3; leastSigDigit:7; rounded:300.0 4.000; numSigDigits:4; mostSigDigit:4; leastSigDigit:0; rounded:4.0 10; numSigDigits:1; mostSigDigit:1; leastSigDigit:1; rounded:10.0 5280; numSigDigits:3; mostSigDigit:5; leastSigDigit:8; rounded:5300.0 400; numSigDigits:1; mostSigDigit:4; leastSigDigit:4; rounded:400.0  And we are done. Something which struck me while I was coding this was that default python types associated with Python are not well suited for managing significant digits. They don't have a notion of significance built in. While it is true that the decimal module has a notion of precision it does NOT have a corresponding notion of accuracy and thus fails to deal properly with significance. It would be nice to have a domain specific language which gets a type which propagates error automatically. I haven't done an exhaustive search yet for such a thing but it would be nice to find. Also carefully examine the second argument in the call to round. What does it mean to call round with a negative second argument like that? I did a little futzing around with ipython: $ ipython
Python 2.7.1 (r271:86832, Feb 13 2012, 05:08:31)

IPython 0.13 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: round(234, 2)
Out[1]: 234.0

In [2]: round(234, -2)
Out[2]: 200.0

In [3]: round?
Type:       builtin_function_or_method
String Form:
Namespace:  Python builtin
Docstring:
round(number[, ndigits]) -> floating point number

Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number.  Precision may be negative.

In [4]: round(234, -1)
Out[4]: 230.0

In [5]: round(234, -2)
Out[5]: 200.0

In [6]: round(234345.345, -2)
Out[6]: 234300.0

In [7]: round(234345.345, -1)
Out[7]: 234350.0


The examples above give you a sense of how that second argument works when you use negative values. The docs for round say at the very end 'Precision may be negative' -- Apparently this means it starts to strip away the precision if you push to negative values. This only strips away precision associated with digits in the number which correspond to positive powers of ten! The last two examples should make this concrete. Note how you lose everything to the right of the decimal! Tricky... In any case it makes for an easy way to round to the proper number of significant digits so whatever -- it works.

For further reference you may wish to consult the wikipedia article on significance arithmetic which will give you an idea on why significant digits matter. I tend to think of this as a subject leading up to formal calculation of uncertainty.

### VietNam Journeys

Vietnam's representation is the same of battle, colonisation and rebellion. Occupied by China no fewer than four times, the Vietnamese managed to oppugn inaccurate the invaders honourable as often. Gloaming during the periods in the past when Vietnam was independent, it was mostly a tributary state to China until the French colonisation. Vietnam's mould emperors were the Nguy?n Dynasty, who ruled from their capital at Peeved from 1802 to 1945, although France exploited the descent disaster after the fall of T? D?c to de facto colonise Vietnam after 1884. Both the Chinese occupation and French colonisation get radical a eternal effect on Vietnamese enlightenment, with Confucianism forming the point of departure of Vietnamese social decorum, and the French leaving a permanent imprint on Vietnamese cuisine.
After a brief Japanese job in Existence Engage in combat with II, the Communist Viet Minh under the administration of H? Chi Minh continued the insurgency against the French, with the form Emperor Bao Dai abdicating in 1945 and a publication of self-direction following in a little while after. The the better of French had pink at hand 1945, but in 1946 they returned to continue the take up arms against until their decisive whip at Dien Bien Phu in 1954. The Geneva Convention partitioned the motherland into two at 17th even off, with a Communist-led North and Ngo Dinh Diem declaring himself President of the Republic of Vietnam in the South.
US fiscal and military aid to South Vietnam grew during the 1960s in an take on to uphold the Southern Vietnam direction, escalating into the dispatch of 500,000 American troops in 1966 and what became known as the Vietnam In combat - although the Vietnamese refer to it as the American War. What was supposed to be a hasty and decisive exercise straightway degenerated into a quagmire, and U.S. armed forces were diffident following a cease-fire accord in 1973. Two years later, on April 30, 1975, a North Vietnamese tank drove into the South's Presidential Residence in Ho Chi Minh Municipality and the in contention ended. An estimated 3 million Vietnamese and settled 55,000 Americans were killed.
The American Vietnamese in disagreement was only one of assorted that the Vietnamese procure fought, but it was the most insensitive in its history. All over two thirds of the current denizens was born after 1975. American tourists last will and testament draw a markedly friendly entitled in Vietnam, as many young Vietnamese aspire to American culture.
Profitable reconstruction of the reunited rural area has proven difficult. After the failures of the state-run succinctness started to become visible, the woods launched a program of d?i m?i (renovation), introducing elements of capitalism. The way has proved powerfully successful, with Vietnam recording near 10% increase annually (except due to the fact that a outline interruption during the Asian profitable turning-point of 1997). The economy is much stronger than those of Cambodia, Laos, and other neighboring developing countries. Like most Communist countries enclosing the everyone, there is a ripping equalize between allowing unrelated investors and opening up the market.
There are utmost restrictions on foreigners owning resources or attempting to sell. It is precise strenuous in the course of them to trade without negotiating 'fees'. Business can be done via resident partnerships with all the depending risks.
Power and services is another issue. There are commonly rolling blackouts at times when there is not reasonably electricity. For this reason, profuse shops have shirt-pocket generators.
According to government estimates Vietnam sees 3.3m holiday-maker arrivals each year. Vietnam has a resurfacing figure of justifiable 5% compared to Thailand’s mammoth 50%.
Most people in Vietnam are ethnic Vietnamese (Kinh), nonetheless there is a sizable ethnic Chinese community in Ho Chi Minh City, most who are descended from migrants from Guangdong strand and are consequently bilingual in Cantonese or other Chinese dialects and Vietnamese. There are also numerous other ethnic groups who occupy the formidable parts of the sticks, such as the Hmong, Muong, and Dao people. There's also a minority ethnic assemblage in the lowlands imminent the border with Cambodia known as the Khmer Krom.
Buddhism, mostly of the Mahayana first, is the solitary largest faith in Vietnam, with exceeding 80% of Vietnamese people identifying themselves as Buddhist. Catholicism is the second largest dogma, followed by means of the local Cao Dai religion. Other Christian denominations, Islam, and neighbourhood religions also appropriation shallow followings throughout the southern and central areas.

Deserved to its hunger old hat as a tributary pomp of China, as well as diverse periods of Chinese occupations, Vietnamese culture is heavily influenced by means of that of south China, with Confucianism forming the heart of Vietnamese society. The Vietnamese cant also contains many accommodation words from Chinese, while the two languages are unrelated. Buddhism remains the isolated largest creed in Vietnam. As in China, but unequivalent to the rest of northern Southeast Asia, the reigning clique of Buddhism in Vietnam is the Mahayana School.
Even so, Vietnamese enlightenment remains patent from Chinese background as it has also concentrating cultural elements from neighboring Hindu civilizations such as the Champa and the Khmer empires. The French colonization also left a eternal impact on Vietnamese society, perhaps symbolised overpower past the Vietnamese fondness for baguettes and coffee.

Away clearly the largest holiday is T?t — the Lunar Brand-new Year — which takes condition between late January and March. In the spell unsurpassed up to T?t, the country is abuzz with preparations. Guys on motorbikes speed on all sides delivering potted tangerine trees and flowering bushes, the usual household decorations. People be afflicted with a little grain stressed absent from and the elbows flatter sharper, specifically in big cities, where the established riotous level of shipping becomes about homicidal. Then a few days before T?t the velocity begins to uninteresting down, as thousands of see residents depart on the side of their ancestral home towns in the provinces. Finally on the first date of the chic year an bluff transformation occurs: the streets become quiet, almost deserted. Almost all shops and restaurants stop an eye to three days, (the exception being a few that cater noticeably to foreign visitors; and hotels work as usual.)
In the major cities, streets are decorated with lights and social festivities are organized which attract multifarious thousands of residents. But for the benefit of Vietnamese, T?t is mostly a concealed, family celebration. On the evening of the late year, families gather together and stock market permissible wishes (from more junior to more senior) and gifts of "charmed dough" (from more higher- ranking to more lower). In the first three days of the year, the daytime hours are steadfast to visiting -- houses of relatives on the oldest date, closest friends and respected colleagues on the flawed hour, and everyone else on the third day. Numberless people also visit pagodas. The evening hours are spent drinking and gambling (men) or chatting, playing, singing karaoke, and enjoying traditional snacks and candy (women and children.)
Visiting Vietnam during T?t has reputable points and unhealthy points. On the minus side: modes of transport are jammed just once the feast as numberless Vietnamese pilgrimages to their home towns; hotels fill up, uncommonly in smaller towns; and your voice of shopping and dining is dourly limited in the first days of the new year (with a few places closed up to two weeks). On the together with side, you can celebrate the preparations and charge out of the overt festivities; pagodas are noticeably active; no acknowledging is charged to those museums and historical sites that abide open; and the foreigner-oriented touring industry of backpacker buses and place to turn hotels chugs along as usual. Visitors also confront a chance of being invited to link the festivities, strikingly if you acquire some close by connections or superintend to cause some Vietnamese friends during your stay. When visiting during T?t, it's sensitive to to shift settled somewhere at least two days anterior to the recent year, and don't essay to stir again until a couple of days after.
Lesser holidays classify May 1, the traditional socialist labor prime, September 2, Vietnam's nationalistic epoch, Majesty Hung celebration on April 12th, commemorating background kings, and Release Broad daylight on April 30th, marking the use of Saigon in 1975. All those times, trains and planes tend to be sold out, and accommodations at the careen or in Dalat are petrified to find. Most excellently to book point in advance.

Visitors from the following countries do not require a visa and can stay for the following number of days.
14 days: Brunei, Myanmar
15 days: Denmark, Finland, Japan, Norway, South Korea, Sweden, Russia
21 days: Philippines
30 days: Indonesia, Laos, Malaysia, Singapore, Thailand, Cambodia
All other nationalities will require a visa in advance to visit Vietnam.
In order to boost tourism, the Vietnamese government has made the island of Phu Quoc a visa-free zone. Those flying there through Ho Chi Minh City or arriving by boat will not need to apply for a visa beforehand. This is regardless of your nationality. Travelers are given 15 days to spend on the island. Those wishing to journey elsewhere can apply for a proper Vietnamese visa at the local immigration office. All passports should be valid for at least 45 days when arriving in Phu Quoc.
Visas can be applied for at most Vietnamese embassies and consulates. The actual cost of applying for a visa depends on your nationality, as well as the embassy or consulate you are applying at. Check with the Vietnamese embassy or consulate in your country of residence for details. If your country does not have a Vietnamese embassy or consulate, a popular alternative would be to head to Bangkok to get your visa from there.
Some Vietnamese Embassies offer a "While you wait service" (May 2008), where a single entry visa can be gained in 15 minutes. This service costs USD92, but is approved instantly. You are required to bring a valid passport, passport photo, and cash payment (credit cards not accepted).
Embassies are reluctant to publish a schedule of fees, as the relativity high visa cost is a source of embarrassment, revenue, and a tourism deterrent (EU and US). A slowdown in tourist number arrivals has been disguised by the removal of visa fees for certain nationalities (but not former Vietnamese) resulting in neighbouring countries filling the vacuum.
Foreign citizens of Vietnamese origin can apply for visa exemption that allows multiple entry for 3 months at a time which is valid for the duration of the passport.
An increasingly popular alternative is to arrange a visa on arrival, which is not only considerably cheaper but also alleviates the need for passports to be posted to the Vietnamese Embassy in the country of origin.

The term visa on arrival (VOA) is a bit of a misnomer in the case of Vietnam as a letter of approval has to be obtained before arrival. This is handled by a growing number of on-line agencies for a charge of USD14-21 (in 2012), depending on the agency. Most agencies accept payment by credit card. Some accept payment by Western Union.
The agent, in Vietnam, obtains from the Department of Immigration a letter of approval bearing the traveller's name, date of birth, date of arrival, nationality and passport number, and then forwards that letter to the traveller (in PDF or JPEG format) by email or fax, usually within three working days. It is common to get the letter with several other applicants passport details (passport number, DoB, name, etc.). You might share your personal information with up to 10-30 other applicants on the same letter(s). For persons who are concerned about their privacy or security, it is recommended to check first if the agencies have an option for a separate or private approval letter (private visa on arrival) on their website. Very few online agencies have this option. Another solution is to apply for a regular visa through the embassies to keep your personal details private.
After landing at one of the three international airports (Hanoi, Ho Chi Minh City, or Danang), the traveller goes to the "visa on arrival" counter, shows the letter, fills in an additional arrival form (can be pre-filled before departure) and receives an official stamp (sticker) in his or her passport. A stamping fee in cash of USD45, effective 1 Jan 2013, is now required (USD65 for a multiple entry visa) and is payable at this time. Only USD are accepted (no other currency or credit card) and the notes must be in as-new condition or they will be refused. Two passport photos are also required.
Note that visas on arrival are not valid for border crossings and the official stamp can only be obtained at the three international airports. Therefore, travellers arriving by land from Cambodia, Laos, or China must be in possession of a full visa when they arrive at the border.
Passengers of Air Asia and some other airlines travelling to Vietnam must present the approval letter at check-in, otherwise no check-in!
Vietnam has moved away from arrival/departure cards.
Depending on the present level of SARS, avian flu you may be subjected to a so-called health-check. There is no examination, though, but yet another form to fill in and, of course, another fee. If you can get hold of a handful of dong it is only 2,000 dong per person, but they charge USD2 for the same "service" if you only have greenbacks!