Tuesday, July 7, 2009

Patty Cake Vapirew Set

amounts and use of BigDecimal in Java:

The purpose of this note is twofold. First, there is an awareness of the compelling need to use BigDecimal instead of double management applications.

Secondly, we will give some recommendations for effective use of BigDecimal.

Why use BigDecimal and not double

Handling amount of programming has often encountered some problems of comparison, two numbers are supposed to be equal as tested different example is different from 7273.27x10 72732.7.

The storage mechanism traditional binary numbers: a sum of power of 2, is responsible for this problem.

Numbers as simple as 0.1 can not be stored precisely in that form. Therefore 0.1 is never exactly equal to 0.1. So 0.1 x10 is not exactly equal to 1. Out 1 = 2 ^ 0, so it has an accurate representation. If we made a comparison with 0.1 x10 1 gives a result in this case wrong.

NB It seems as if the 0.1 is better treated now since Java, if using double, it has 0.1 x10 = 1.0.

In business applications, numbers are often the amounts or percentages: the number of digits after the comma is usually known (between 2 and 4, see 6 or 8 for some financial applications).

In case of division, there are rules of rounded and it is not desirable to change the storage to gain "precision". These applications do not know the actual: 1 / 3 will be equal to 0.33.

The BigDecimal in Java

In Java, there is a type BigDecimal which can take into account this type of problem: it relies on the fact that an integer has an exact binary representation.

For an amount, simply set the number of digits after the decimal point and store the number as a whole: 7273.27 example will be stored as a value of 727,327 with 2 digits after the decimal point. The number of digits after the decimal point corresponds to the scale property of the BigDecimal.

Using BigDecimal causes a small constraint: it is not a native type but an object. It is therefore not possible to use the operators +, -, * and /.

example

7273.27 * 10.0 which is written with double: double

doubleApproche = 7273.27;
double result = 10 * doubleApproche;

becomes BigDecimal:

BigDecimal = new BigDecimal doubleApproche ("7273.27");
doubleApproche.multiply BigDecimal result = (new BigDecimal (10));

Project Example

We'll create a simple Eclipse project to illustrate the different cases.

menu: File -> New Project

Then select the node in Java: Java Project.

The project name will TestBigDecimal.

Press the Finish button.

On node src, right click and select New -> New JUnit Test Case

the radio button

Things New JUnit 4 test.

Package: fr.j2ltho.test.bigdecimal

Name: TestDifferences

Then press the Finish button.

A dialog box appears: "JUnit 4 is Not On The build path. Do you want to add it?".

Choose the radio button: Perform Action THE FOLLOWING:

And check that there is: Add To The JUnit 4 library build path.

Validate by pressing the OK button.

It adds the following code: package

fr.j2ltho.test.bigdecimal;

import static org.junit.Assert.assertEquals;

import java.math.BigDecimal;

import org.junit.Test ;

TestDifferences public class Test {@
(timeout = 1000) public void
testProblemeDouble () {double
doubleApproche = 7273.27;
        double resultat=10*doubleApproche;
        assertEquals("Double fois 10", 72732.7, resultat);
        if (resultat==72732.7) {
            System.out.println("Egale:  " + resultat);
        }
        else {
            System.out.println("Ecart:  " + (resultat-72732.7));           
        }       
    }
    @Test(timeout=1000)
    public void testProblemeBigDecimal() {
        BigDecimal doubleApproche=new BigDecimal("7273.27");       
        BigDecimal resultat=doubleApproche.multiply(new BigDecimal(10));
        assertEquals("BigDecimal fois 10", new BigDecimal("72732.7"), resultat);
        if (resultat.compareTo(new BigDecimal("72732.7")) ==0){
            System.out.println("Egale:  " + resultat);
        }
        else {
            System.out.println("Ecart:  " + (resultat.subtract(new BigDecimal("72732.7"))));           
        }       
    }
    @Test(timeout=1000)
    public void testDixiemeDouble() {
        double doubleApproche=0.1;       
        double resultat=10*doubleApproche;
        assertEquals("Double fois 10", 1.0, resultat);
        if (result == 1.0) {
System.out.println ("Egal:" + result);

} else {
System.out.println ("Écart:" + (result-1.0));
        }       
    }
    @Test(timeout=1000)
    public void testCentiemeDouble() {
        double doubleApproche=0.01;       
        double resultat=10*doubleApproche;
        assertEquals("Double fois 10", 0.10, resultat);
        if (resultat==0.10) {
            System.out.println("Egale:  " + resultat);
        }
        else {
            System.out.println("Ecart:  " + (resultat-0.10));           
        }       
    }
    @Test(timeout=1000)
    public void testDixiemmeCentiemeDouble() {
        double doubleApproche=0.11;       
        double resultat=10*doubleApproche;
        assertEquals("Double fois 10", 1.10, resultat);
        if (result == 1.10) {
System.out.println ("Egal:" + result);

} else {
System.out.println ("Écart:" + (result-1.10));

}}}

The execution of Test: Run As -> JUnit Test provides a successful test at 100% but with the following result in the Console:

Gap: 1.4551915228366852E-11
Equals: 72732.70
Equals: 1.0
Equals: 0.1 Equal
: 1.1

This shows that the comparison JUnit assertEquals: assertEquals ("Double time 10", 72732.7, result); returns a just result when comparing the double return an error and the difference in returns to differ.

If handling of Java double, beware of assertEquals who seem to take into account a rounding difference.

Creating a BigDecimal

The BigDecimal is an object, it is created with a new. Its constructor accepts a String, a long or a double.

should never use the constructor twice because it reintroduces the problem of the round.

The following test illustrates the problem:

@ Test (timeout = 1000)
testProblemeConstructeurDouble public void () {BigDecimal
doubleApproche = new BigDecimal (7273.27);
BigDecimal = new BigDecimal stringApproche ( "7273.27");
assertEquals ("BigDecimal x 10" doubleApproche, stringApproche)
if (doubleApproche. compareTo (stringApproche) == 0) {
System.out.println("Egale:  " + doubleApproche);
    }
    else {
        System.out.println("Ecart:  " + (doubleApproche.subtract(stringApproche)));           
    }       
}

The console displays:

Gap: 4.3655745685100555419921875E-13

Again, we see that for assertEquals BigDecimal is unreliable because it indicates an equality that is not real.

For integers, it is preferable to use the static method valueOf () that is more readable:

BigDecimal.valueOf (40)

There are three methods to create a static BigDecimal value 1 or 0 or 10.

  • BigDecimal.ONE
  • BigDecimal.ZERO
  • BigDecimal.TEN

In short, it is recommended that:

  • For a fee, rate or a percentage, the constructor with a String parameter: BigDecimal = new BigDecimal stringApproche ("7273.27");
  • For units, the static method valueOf: BigDecimal.valueOf ( 40) For
  • remarkable values 0, 1 and 10: use static methods: BigDecimal.ZERO, and BigDecimal.ONE BigDecimal.TEN

Addition and subtraction with BigDecimal.

Addition and subtraction do not feature in Apart from the requirement to use a method:

  • add subtract

It will for example

BigDecimal value = new BigDecimal ("70.36")
/ / resAddition = value + 1 = valeur.add resAddition
BigDecimal (BigDecimal.ONE)
/ / = value -10 resSoustraction
resSoustraction BigDecimal = valeur.subtract (BigDecimal.TEN)

Multiplication and Division BigDecimal

Multiplication on the same principle that addition and subtraction using the method: multiply.

BigDecimal = new BigDecimal pricePerShare ("70.36");
/ / coutTotal pricePerShare = * 3 = pricePerShare.multiply coutTotal
BigDecimal (BigDecimal.valueOf (3));


For the division is more complicated because it must indicate:

  1. the number by which we divide
  2. but especially the number of digits after the decimal point that we wish to retain the result (a division does not always just fall)
  3. and finally the mechanism rounding: we usually use BigDecimal.ROUND_HALF_UP

For example, the number of shares purchased:

BigDecimal = new BigDecimal pricePerShare ("70.36");
purchaseAmount = BigDecimal.valueOf BigDecimal (200);
/ / = nbPart purchaseAmount / pricePerShare
BigDecimal nbPart = purchaseAmount . divide (pricePerShare, 4, BigDecimal.ROUND_HALF_UP)

There are two methods to simplify multiplication and division by multiples of 10:

  • movePointLeft (2) we move the decimal 2 to the left of which corresponds to a division 100.
  • movePointRight (1) is moved from one point to the right which corresponds to a multiplication by 10.

These two methods are particularly useful when calculating rates or percentages.

BigDecimal total = BigDecimal.valueOf (950);
BigDecimal BigDecimal.valueOf Percentage = (20);
/ / We want 20% of 950
/ / amount = (total * percentage) / 100 = total amount
BigDecimal . multiply (percentage). movePointLeft (2);

comparison method should be promoted: compareTo that ignores the number of digits after the decimal point. compareTo considers that 15.2 and 15 200 are identical. This is not the case with equals ().

The method compareTo returns an integer and not boolean:

  • 0 if the value is identical
  • 1 if the value is greater than the parameter
  • -1 if the value is less than the parameter

In through the use of JUnit we recommend:

assertEquals ("Comparison", 0, doubleApproche.compareTo (stringApproche));

instead of:

assertEquals ("Comparing imprecise "doubleApproche, stringApproche)

Indeed in some cases (small gap): the first show is a difference, while the second will show a tie.

Display

To view a BigDecimal, there are two methods:

  • plainString
  • toString

We recommend using a third solution: the use of formatting with DecimalFormat. this mechanism to force the representation of BigDecimal following a defined format.

The following example is significant: we have deliberately used the double manufacturer to show the difference.

BigDecimal = new BigDecimal doubleApproche (7273.27);

System.out.println ("7273.27 toPlainString:" + doubleApproche.toPlainString ());
System . out.println ("7273.27 toString:" + doubleApproche.toString ());

DecimalFormat DecimalFormat = new DecimalFormat ("##,###,###,## 0.00 ");
System.out. println ("7273.27 DecimalFormat:" + decimalFormat.format (doubleApproche));

Conclusion

Using BigDecimal is a little heavier than double. But there are a set of methods to streamline work and especially the assurance of not having a problem rounding at the end.

This forces us to disambiguate the choice of rounding early: This avoids disappointment with the business teams during the phases of recipe. The business teams are fully aware of these rules, they they are so natural that they forget to specify them. Using BigDecimal forces us to determine from the beginning of the program what to do.

Monday, May 25, 2009

Numéro Série Néro 3.1

AppStore: Analysis of a successful

This post is part of a broader debate on the issues revolutionary iPhone. It focuses on the AppStore whose success goes beyond numbers provided by Apple: 35 000 applications and a billion downloads of May 2009 (press release from Apple: http://www.apple.com / fr/pr/library/2009/04/24appstore.html? sr = Hotnews ). This approach

market place has been taken from Google, Nokia, RIM and Microsoft (for BlackBerry). The concept seems to be sufficiently novel and interesting to be taken by the competition.

Since April 2009, advertisements for the iPhone focuses exclusively on the applications available on AppStore rather than on the iPhone itself. It is a sign of the importance of the ecosystem iPhone in the purchase decision. And who better symbolizes the AppStore this ecosystem. The AppStore

Beginning with the AppStore soon present especially for readers who are not familiar with the iPhone. The AppStore is a great market applications for iPhone and iPod Touch. It is priced applications and free applications.

The AppStore is a department of the famous iTunes Store (the world leader in music sales). It is available from the iTunes software: To navigate through the AppStore, so it is not necessary own an iPhone, just use iTunes. There is a version of the iPhone AppStore, it is possible to view and download applications directly from the iPhone.

The AppStore has different grading applications: in general there are two separate classifications: one for free applications and one for paid applications. Free applications are not hidden or buried at the bottom of the site they have the same visibility as paid applications.

Extent of success of the AppStore

Apple Announces 35 000 applications worldwide, 10,000 available for France. The figure speaks for itself and it is hard not to find the application you need.

Of the 10 000 applications, we will find in the News section by an application for this newspaper and the entire world press. It will thus find an application to:

  • reading World
  • reading the New York Times
  • reading El Pais (Spain)

And many more. Note that this is three different applications.

iPhone can also be used as book reader: it is possible to buy books in electronic format: in this case, a book is an application.

These examples are given to show the actual number of applications is in practice less than 10 000. Nevertheless, it remains very important and probably beyond what is available on competing platforms.

Apple announces one billion downloads: we can estimate the number of iPhones sold around 20 million. It would therefore be on average 50 per iPhone download. That seems excessive. I think Apple has a download for updating. For example, readers of The New York Times that I use had to be updated a dozen times: Apple probably has 10 downloads.

That said, all applications have few versions and what is more: a user is not obliged to make the update. One the other, I think a user has loaded an average of about twenty different applications. This figure is very important if we consider that this is an average for a consumer product composed mainly of non computer.

At the time I loaded on my Palm 4 or 5 applications in 4 years of use. On the iPhone and through the AppStore, an average user has downloaded a twenty applications in 9 months of use.

Such an increase (factor 4) on as wide a population can be the fact that a major change, revolutionary. It is this or these changes we will identify. My Applications

Before going further in the analysis, I will list the 29 applications I installed on my iPhone it will illustrate the different types of applications.

  • news sites:
    • ElPais.com: application of the newspaper El Pais (Spain) The
    • Monde.fr: application of the World. It allows offline reading of sections of the site. Attention items are shorter than those of the printed newspaper.
    • NYTimes: Applying the New York Times (USA). The papers seem full (They are much longer than those of the World) but the offline mode does not.
    • Sports.fr: A sports newspaper with a live mode that tracks sporting events (such as a day of championship soccer) live.
  • Games Crash Bandicoot Nitro
    • : A kind of Mario Kart that uses the accelerometer. For me the level of Mario Kart for Nintendo DS with the exception of multi-player mode is not available.
    • Hanoi: The puzzle towers of Hanoi
    • iChess (Free): a chess
    • Mastermind: the game of MasterMind
    • TouchMines: a version of Minesweeper. A bit difficult to play because the boxes are too small. Virtual Pool
    • Lite: a very good game of pool which makes it very well the feelings of real billiards.
  • productivity applications
    • SimpleMind Xpress: An application of brainstorming
    • Evernote: a great application for taking notes which are spoken, written or also photo taken with the iPhone. There is also a for Windows and a Firefox plug-in to rate music by website.
  • references and dictionaries
    • dictionary Littré: a very old version and just past that the dictionary Littré I use words to explain to children
    • PagesJaunes: this application extends the Web site by making available the use of localization.
    • Wapedia - Wiki Mobile: A very friendly version of Wikipedia for the iPhone.
    • 160 000 Recipes: A recipe site (in English)
  • Help moving
    • Wikango: an excellent warning radar
    • PanameTraffic: To view the traffic on the Paris region, become a little less useful since the traffic is also available directly on the implementation plan (Google Map)
    • GoVelib: To know the Velib stations around you and their availability cycling.
    • Locly: to understand a few types of businesses or services (such as ATM card blue) around you.
  • Entertainment
    • Liveradio Orange can listen to radio stations over the Internet.
    • First: The latest film critics with sessions near you.
    • Stanza: a book reader for iPhone. The application allows the downloading of large quantities of books in English or French (all old).
  • Utilities
    • Orange spot'finder: Enables you to find the Hot Spot WiFi around you.
    • Speedtest: Measures the speed of your Internet connection. One application which has in August / September 2009 to highlight the clamping of the Orange 3G.
    • 9 - Toolbox (Free Event): a series of small utility that runs from the unit converter spirit level
  • Social Networks
    • LinkedIn: the application to connect to professional social networking site LinkedIn
  • The gaming applications
    • Lightsaber Unleashed: A Star Wars lightsaber. Ideal to impress young children.
  • Applications advertising
    • Angoulême 2009: Application created for the festival of Angoulême BD who can flip a series of comics.

From this list of applications only Crash Bandicoot Nitro Kart 3D pays off: the rate of 5 € price is very competitive with a Nintendo DS at 35 €.

Benefits

The concept AppStore AppStore may be regarded as deriving from the iTunes Store: a marketplace for applications. It enjoys the same advantages:

  • simplifies the search: it is not necessary to search multiple stores or on different sites which application is best or what application is available. Just go to the AppStore and see if there is a new application that might interest us.

But the AppStore adds a characteristic application markets:

  • confidence in applications: applications are "validated" by Apple. Even if you do not know what it really implies, it is certain that this excluded the virus.
  • Creating a market place has had another benefit for users: the competition between producers of applications to cause a significant drop in prices: the majority of game publishers have launched their games at prices close to 17 $ few days later regained the same games around $ 7. So, there are many applications at prices significantly lower on the iPhone than on competing platforms. In my list Crash Bandicoot Nitro Kart is a great example: for 5 € was a game that would be € 35 for Nintendo DS.

These three points certainly explain the one billion downloads in less than a year.

The AppStore as a social bond

confidence and simplicity to grow downloads "fun" I mean, downloading of applications (often free) just to see what they do. It does not necessarily seek the utility side but the "fun": a mixture of surprise and "fun", see a lag. These are applications that we will show that will serve to initiate a discussion: it serves to create a social bond between two people is sometimes used as a newspaper article, an event where more systematically a sporting event.

Among these applications we find the emblematic Shazam that can recognize a song and that is regularly used in Apple advertising. In my list, you will find Light Saber that can bind the conversation with children. Some small games are also ideal for little short they are simple and fun.

In the list of applications you will find a box silly moo (moo fact that when the returns), a whoopee cushion, aquariums ... These downloads

"fun" is a real phenomenon among iPhone users and can easily account for a third of downloads. This phenomenon is even stronger than with the iPhone version of the AppStore, the viewer can move quickly conquered download the new application immediately and with confidence because it hosted on a site controlled by Apple.

This type of behavior would not be as important (a half-dozen download per person on average) without the feeling of confidence inspired by the AppStore: the stroke of genius from Apple. This is a revolution in user behavior even if I should limit its usefulness seems to me.

Beyond this playfulness, the choice of a lot of applications must also be some affirmation of identity of the owner of the iPhone: the choice of a newspaper is not neutral for example. We find a modern equivalent of family libraries for displaying through the selection of books placed prominently on the shelves social status. It is applications like books: not because it is present on an iPhone it is used. Conclusion

The AppStore is a breakthrough offering iPhone behavioral changes that resulted. This change was possible only because users felt confident about the existence of a market place under the control of the manufacturer.

What is revolutionary is the attention and importance that is Apple's ecosystem, many analysts have explained the defeat of MacOS on Windows by the little attention that Apple developers had to wear while they have always been pampered by Microsoft. The lesson seems to have been chosen by Steve Jobs and the thousands of expected new API with the 3.0 firmware of the iPhone should not deny this change.