I am pretty new to Java. I am learning numerical computation at the moment. How does one add and multiply a very small number and a very large number, say something of order $10^{-20}$ and something of order $10^{20}$ to arbitrary precision.
Take a look at the BigDecimal class. From the Javadoc:
Immutable, arbitrary-precision signed decimal numbers.
and:
The BigDecimal class gives its user complete control over rounding behavior.
For your example:
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal big = new BigDecimal("10e20");
BigDecimal small = new BigDecimal("10e-20");
BigDecimal ans = big.add(small);
System.err.println("Answer: " + ans);
}
}
Running gives the following:
$ java Main
Answer: 1000000000000000000000.00000000000000000010
Try the following (didn't count the zeros). You may find other methods to construct 10^20/10^-20 more suitable.
System.out.println( new BigDecimal("0.0000000000000000000000000000001").add( new BigDecimal
("100000000000000000000000000000000")));
Related
public class Dummy {
public static void main(String args[]) {
String x = "1.234.567,89 EUR";
String e = " EUR";
List<BigDecimal> totals = new ArrayList<BigDecimal>();
totals.add( new BigDecimal(x.replaceAll(" EUR","").replaceAll("\\.","").replaceAll(",",".")));
System.out.println(totals.get(0).add(new BigDecimal(0.10).setScale(3,0)));
}
}
With current code I get 1234567.991 and setting it to setScale(2,0) I get 1234568.00 what I am looking for is 1234567.99. Any help?
Use
System.out.println(totals.get(0).add(new BigDecimal(0.10)
.setScale(2, BigDecimal.ROUND_HALF_UP)));
Out put
1234567.99
I think there must be an inbuilt Java function for this. But otherwise, you can do it with simple mathematics.
You can multiply the number with 100. And then use ceiling or floor function of Java. And then divide it with 100. You got your desired result.
Do not use
new BigDecimal(0.10)
which is both inprecise and does not give a precision/scale of 2.
But use
new BigDecimal("0.10")
This preserves the scale.
This will give desired output.
If you want to go with double at that time we can use DecimalFormat but in bigdecimal setScale is used.
BigDecimal.valueOf(1234567.991).setScale(2, BigDecimal.ROUND_HALF_UP)
.doubleValue();
OUTPUT
1234567.99
Currently, using DecimalFormat I would like to show maximum number of decimal places, or don't show at all. For instance,
100.0 shown as "100"
100.123 shown as "100.123"
100.123456789012345 shown as "100.123456789012345"
Using format as
new DecimalFormat("0.###"); is partially correct. It works for 1st case, 2nd case but not 3rd case. As, I have no idea how much # should I have?
So, may I know what is the correct DecimalFormat I should use?
You can use setMaximumFractionDigits() to do this. The maximum value is 340, so might as well set it to that value:
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat();
formatter.setMaximumFractionDigits(340);
BigDecimal[] numbers = {new BigDecimal("100.0"), new BigDecimal("100.123"), new BigDecimal("100.123456789012345")};
for (BigDecimal number : numbers) {
System.out.println(formatter.format(number));
}
}
prints
100
100.123
100.123456789012345
I am creating a small game for students, and in a place, it has to display the value of 27830457+1
I can call BigInteger's pow() method if the number is not this much big. Since the number is very big, that method is useless. How can I find the HUGE power of this kind of numbers? Please help!
Well in binary it's just 10000...01 with 7830456 zeros.
In decimal, there will be approximately two million digits, which is about 2 megabytes of storage. This is well within the feasibility of BigInteger with a default heap size.
In practice, it even uses exponentiation by squaring to compute it quickly (though not guaranteed by the specifications). However the conversion to a String will take some time since it's a linear time operation.
import java.math.BigInteger;
public class BigPow {
public static void main(String[] args) {
BigInteger result = (new BigInteger("2")).pow(27830457).add(BigInteger.ONE);
System.out.println(result);
}
}
Here's a version which will print out the digits slowly:
import java.math.BigInteger;
public class BigPow {
public static void main(String[] args) {
BigInteger result = (new BigInteger("2")).pow(27830457).add(BigInteger.ONE);
BigInteger powten = BigInteger.TEN.pow(2357202);
while(powten.compareTo(BigInteger.TEN) > 0) {
BigInteger digit = result.divide(powten).mod(BigInteger.TEN);
System.out.print(digit);
powten = powten.divide(BigInteger.TEN);
}
}
}
The first digits are:
27337386390628313557307248857732033008168556429738078791761607160549944954510637855005417718646965163546351365984857761796847950377880836291434244529029919271706271982523405687134334692691344477538489450971091437463160940371624647030064741968436401566711255284353690448270545402444641547030399228243743315193608710148721648879085592699913299745785392609301774185427367430782834290629265859073814466687714408436025809860462926275610087354595992436000187216152954542774991509992374985538879880897902639600451627914923043483436514419544413306391278529303650112773297502090619459167888563274071587848623085880067091968911236296732119252937497152769541579516150659424997041968213122450568364121976474269097910635641227922923398092242409755554115985855831015459204780391470591543281267373716556272259386683864538263922398723602210173800151405332100275913619559563575829498369806957031526077258236305186254269056811134135133350936924294101345294335698866339561918857584229744277901180792029180156485000086528174400878657004645726892816943589969701053158760210512171516969813345080894134663207988962182426459128577282934948790911691329475034324656384238413230485050607666988301932660490870167246016897007835866691705399794247746213819662270451531049826029606671683482160663572103374
Confirmed by WolframAlpha.
I don't know why you think BigInteger isn't up to this:
import java.math.BigInteger;
public class Test {
public static void main(String[] args) throws Exception {
BigInteger big = BigInteger.valueOf(2)
.pow(7830457)
.add(BigInteger.ONE);
System.out.println(big);
}
}
It takes a little while (particularly the string conversion at the end), but it's perfectly reasonable.
As Peter noted, shifting ONE left 7830457 is much neater, mind you. I'd argue it's a bit less clear - and of course it doesn't help in the string conversion part.
EDIT: Almost all of the time is spent in the string conversion. It finished in the end on my box though. I can't see the start of it any more, but it ends with...
08570502260645006898157834607641626568029302766491883299164453304032280181734737
79366998940913082443120328458954436211937775477966920836932628607888755839700303
873
You should be able to calculate this with BigInteger.
System.out.println(BigInteger.ONE.shiftLeft(7830457).add(BigInteger.ONE));
Try something like this:
BigInteger mant = new BigInteger("2");
BigInteger result = mant.pow(7830457).add(BigInteger.ONE);
I'm using this basic and crude code below for calculating prime numbers then exporting them to a text file:
import java.util.Scanner;
import java.io.*;
public class primeGenerator{
public static void main(String[] args)throws Exception {
Scanner kb = new Scanner(System.in);
String prime;
long num = kb.nextLong();
long i;
long z=0;
while(z==0){
for (i=2; i < num ;i++ ){
long n = num%i;
if (n==0){
break;
}
}
if(i == num){
writer(num);
}
num=num+2;
}
}
public static void writer(long num) throws Exception {
FileWriter writer = new FileWriter("prime.txt",true);
String prime= ""+ num;
writer.write(prime);
writer.write(" ");
writer.flush();
writer.close();
}
}
I would like to find primes beyond the Primative long's range and apparently big integer is the way to go about it. So how do i alter my code to do so?
Do you really need this? Having numbers bigger than can be handled by long means you want to test numbers bigger than 9223372036854775807. If your for-loop can test a hundred million divisions per second, it will still take it 2923 years to determine if that number is prime - and longer for larger numbers, of course.
A common optimization is to only test divisions up to sqrt(num). If you haven't found anything then, the number is prime.
Well, use BigInteger wherever you've currently got long. Instead of using % you'll use mod, instead of incrementing you'll use i = i.add(BigInteger.ONE), instead of == 0 you'll use equals(BigInteger.ZERO) etc.
Use Scanner.nextBigInteger instead of Scanner.nextLong, too.
Given that this looks like homework of some description (possibly self-set, of course) I won't write out the whole code for you - but if you have specific problems, feel free to ask.
I was trying to make my own class for currencies using longs, but apparently I should use BigDecimal instead. Could someone help me get started? What would be the best way to use BigDecimals for dollar currencies, like making it at least but no more than 2 decimal places for the cents, etc. The API for BigDecimal is huge, and I don't know which methods to use. Also, BigDecimal has better precision, but isn't that all lost if it passes through a double? if I do new BigDecimal(24.99), how will it be different than using a double? Or should I use the constructor that uses a String instead?
Here are a few hints:
Use BigDecimal for computations if you need the precision that it offers (Money values often need this).
Use the NumberFormat class for display. This class will take care of localization issues for amounts in different currencies. However, it will take in only primitives; therefore, if you can accept the small change in accuracy due to transformation to a double, you could use this class.
When using the NumberFormat class, use the scale() method on the BigDecimal instance to set the precision and the rounding method.
PS: In case you were wondering, BigDecimal is always better than double, when you have to represent money values in Java.
PPS:
Creating BigDecimal instances
This is fairly simple since BigDecimal provides constructors to take in primitive values, and String objects. You could use those, preferably the one taking the String object. For example,
BigDecimal modelVal = new BigDecimal("24.455");
BigDecimal displayVal = modelVal.setScale(2, RoundingMode.HALF_EVEN);
Displaying BigDecimal instances
You could use the setMinimumFractionDigits and setMaximumFractionDigits method calls to restrict the amount of data being displayed.
NumberFormat usdCostFormat = NumberFormat.getCurrencyInstance(Locale.US);
usdCostFormat.setMinimumFractionDigits( 1 );
usdCostFormat.setMaximumFractionDigits( 2 );
System.out.println( usdCostFormat.format(displayVal.doubleValue()) );
I would recommend a little research on Money Pattern. Martin Fowler in his book Analysis pattern has covered this in more detail.
public class Money {
private static final Currency USD = Currency.getInstance("USD");
private static final RoundingMode DEFAULT_ROUNDING = RoundingMode.HALF_EVEN;
private final BigDecimal amount;
private final Currency currency;
public static Money dollars(BigDecimal amount) {
return new Money(amount, USD);
}
Money(BigDecimal amount, Currency currency) {
this(amount, currency, DEFAULT_ROUNDING);
}
Money(BigDecimal amount, Currency currency, RoundingMode rounding) {
this.currency = currency;
this.amount = amount.setScale(currency.getDefaultFractionDigits(), rounding);
}
public BigDecimal getAmount() {
return amount;
}
public Currency getCurrency() {
return currency;
}
#Override
public String toString() {
return getCurrency().getSymbol() + " " + getAmount();
}
public String toString(Locale locale) {
return getCurrency().getSymbol(locale) + " " + getAmount();
}
}
Coming to the usage:
You would represent all monies using Money object as opposed to BigDecimal. Representing money as big decimal will mean that you will have the to format the money every where you display it. Just imagine if the display standard changes. You will have to make the edits all over the place. Instead using the Money pattern you centralize the formatting of money to a single location.
Money price = Money.dollars(38.28);
System.out.println(price);
Or, wait for JSR-354. Java Money and Currency API coming soon!
1) If you are limited to the double precision, one reason to use BigDecimals is to realize operations with the BigDecimals created from the doubles.
2) The BigDecimal consists of an arbitrary precision integer unscaled value and a non-negative 32-bit integer scale, while the double wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double
3) It should make no difference
You should have no difficulties with the $ and precision. One way to do it is using System.out.printf
Use BigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP) when you want to round up to the 2 decimal points for cents. Be aware of rounding off error when you do calculations though. You need to be consistent when you will be doing the rounding of money value. Either do the rounding right at the end just once after all calculations are done, or apply rounding to each value before doing any calculations. Which one to use would depend on your business requirement, but generally, I think doing rounding right at the end seems to make a better sense to me.
Use a String when you construct BigDecimal for money value. If you use double, it will have a trailing floating point values at the end. This is due to computer architecture regarding how double/float values are represented in binary format.
Primitive numeric types are useful for storing single values in memory. But when dealing with calculation using double and float types, there is a problems with the rounding.It happens because memory representation doesn't map exactly to the value. For example, a double value is supposed to take 64 bits but Java doesn't use all 64 bits.It only stores what it thinks the important parts of the number. So you can arrive to the wrong values when you adding values together of the float or double type.
Please see a short clip https://youtu.be/EXxUSz9x7BM
I would be radical. No BigDecimal.
Here is a great article
https://lemnik.wordpress.com/2011/03/25/bigdecimal-and-your-money/
Ideas from here.
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
testConstructors();
testEqualsAndCompare();
testArithmetic();
}
private static void testEqualsAndCompare() {
final BigDecimal zero = new BigDecimal("0.0");
final BigDecimal zerozero = new BigDecimal("0.00");
boolean zerosAreEqual = zero.equals(zerozero);
boolean zerosAreEqual2 = zerozero.equals(zero);
System.out.println("zerosAreEqual: " + zerosAreEqual + " " + zerosAreEqual2);
int zerosCompare = zero.compareTo(zerozero);
int zerosCompare2 = zerozero.compareTo(zero);
System.out.println("zerosCompare: " + zerosCompare + " " + zerosCompare2);
}
private static void testArithmetic() {
try {
BigDecimal value = new BigDecimal(1);
value = value.divide(new BigDecimal(3));
System.out.println(value);
} catch (ArithmeticException e) {
System.out.println("Failed to devide. " + e.getMessage());
}
}
private static void testConstructors() {
double doubleValue = 35.7;
BigDecimal fromDouble = new BigDecimal(doubleValue);
BigDecimal fromString = new BigDecimal("35.7");
boolean decimalsEqual = fromDouble.equals(fromString);
boolean decimalsEqual2 = fromString.equals(fromDouble);
System.out.println("From double: " + fromDouble);
System.out.println("decimalsEqual: " + decimalsEqual + " " + decimalsEqual2);
}
}
It prints
From double: 35.7000000000000028421709430404007434844970703125
decimalsEqual: false false
zerosAreEqual: false false
zerosCompare: 0 0
Failed to devide. Non-terminating decimal expansion; no exact representable decimal result.
How about storing BigDecimal into a database? Hell, it also stores as a double value??? At least, if I use mongoDb without any advanced configuration it will store BigDecimal.TEN as 1E1.
Possible solutions?
I came with one - use String to store BigDecimal in Java as a String into the database. You have validation, for example #NotNull, #Min(10), etc... Then you can use a trigger on update or save to check if current string is a number you need. There are no triggers for mongo though.
Is there a built-in way for Mongodb trigger function calls?
There is one drawback I am having fun around - BigDecimal as String in Swagger defenition
I need to generate swagger, so our front-end team understands that I pass them a number presented as a String. DateTime for example presented as a String.
There is another cool solution I read in the article above...
Use long to store precise numbers.
A standard long value can store the current value of the Unites States national debt (as cents, not dollars) 6477 times without any overflow. Whats more: it’s an integer type, not a floating point. This makes it easier and accurate to work with, and a guaranteed behavior.
Update
https://stackoverflow.com/a/27978223/4587961
Maybe in the future MongoDb will add support for BigDecimal.
https://jira.mongodb.org/browse/SERVER-1393
3.3.8 seems to have this done.
It is an example of the second approach. Use scaling.
http://www.technology-ebay.de/the-teams/mobile-de/blog/mapping-bigdecimals-with-morphia-for-mongodb.html
There is an extensive example of how to do this on javapractices.com. See in particular the Money class, which is meant to make monetary calculations simpler than using BigDecimal directly.
The design of this Money class is intended to make expressions more natural. For example:
if ( amount.lt(hundred) ) {
cost = amount.times(price);
}
The WEB4J tool has a similar class, called Decimal, which is a bit more polished than the Money class.
NumberFormat.getNumberInstance(java.util.Locale.US).format(num);