base-n series generator for a given number in java,, - java

I want to create a program for generating the series for the given base-n. ,
for example if my input is 2,then series shuould be, 00,01,10,11,etc.,(binary)
if my input is 10,then series shuould be,1,2,3,4,5,etc.,(decimal)
is there any general mechanism to find these numbers so that I can program for base-n.,
UPDATE:-
After,working out.,i face issue.
If I want to process that integer how to do that? Some body commented that, BaseInteger class I should use. please elaborate

You could use Integer's toString(int i, int radix) method for that.
For example:
Integer.toString(2, 2) // number 2, base 2
returns the string:
"10"
Note that the radix should be between 1 and 36.

You might be looking for something like this (take a peek at "Algorithm: Constructing Base b
Expansions"):
https://docs.google.com/viewer?url=http://websupport1.citytech.cuny.edu/faculty/dkahrobaei/Integers%2520and%2520Algorithms.pdf

I think you should first figure in which format you need the results. If they should be Strings, Bart's answer would probably suit you. An integer representation, which does actually mean something else (e.g. the int 10 does mean 2 with base 2) seems awkward to me. If i would need something like you described, i would probably implement a BaseNumber class first.

Related

Multiple arithimetic operator store

I have been thinking to solve any problem like 1+2*4-5 with user entering it and program to solve it. I've read some questions on this site about storing arithmetic operator and the solution says to check by using switch which can't be applied here. I would be thankful if anybody could suggest any idea of how to make it.
I had a similar exercise not long ago, but in the question it was stated that the seperation is a space. So the user input would be 1 + 2 * 4 - 5, and i solved it that way. I will give you some tips but not paste the whole code.
-you read the input as a String
-you can use the String.split() method to devide the String into the pieces you need and they will be put in an array.(in this case: strArray[0]='1',strArray[1]='+', etc)
-you will need a for-loop to go trough every String in the array:
-the decimals will need to be converted to integers with the Integer.parseInt() method.
-The + - * / will need to be put in switch-statement.
(be careful how you construct your loop, think about how many times you want to go trough it and what you need in each loop)
I hope these tips helped.

BigDecimal precision above 1E22

for some reason I found myself coding some piece of software, that should be able to perfom some astronomic calculations.
While most of it will be about transfering the correct formula into Java, I found an annoying Problem right at the verry beginning of my "test how to calculate big numbers".
Well... Imagine the Sun (our Sun), which has a mass of (about and rounded, for more easy explaining) 10E30 kg. Ten with 30 following Zeros. All native datatypes are just unusuable for this. To mention: I KNOW that I could use 3000 to calculate things and just add trailing zeros in the output-view, but I hoped to keep it as precise as possible. So using short numbers will be my last resort only.
Comming to the Problem. Please have a look at the code:
BigDecimal combinedMass = new BigDecimal(1E22);
int massDistribution = 10;
Integer mD1 = massDistribution;
Integer mD2 = 100 - massDistribution;
BigDecimal starMass;
BigDecimal systemMass;
systemMass = combinedMass.divide(new BigDecimal("100")).multiply(new BigDecimal(mD1.toString()));
starMass = combinedMass.divide(new BigDecimal("100")).multiply(new BigDecimal(mD2.toString()));
System.out.println((systemMass).toEngineeringString());
System.out.println((starMass));
It will output 1000000000000000000000 and 9000000000000000000000, whats exactly what I did expect. But look at the combineMass Field. If I raise it to 1E23, the Output will change
I get 9999999999999999161139.20 and 89999999999999992450252.80...
So I know I could use jut BigInteger, because its more reliable in this case, but for the sake of precicion, sometimes the BigWhatEver may drop to something like 50.1258
Plus, I hope to get the 10.xE30 as output, whats only possible using bigDecimals.
I want to know: Is there no way avoidng this (that error appers above 1E23 for every value I tried), while keeping the ability to calculate Floating-Points? Should I cut the After-Decimal-Separator-Values for this Field to two digets?
And for something more to wonder about:
System.out.println(combinedMass.precision());
in relation with the code above will provide 23 for that case, but En+1 for most other values (Thats was when I grow really confused)
Thanks for advise.
You're using basic types without realizing it:
new BigDecimal(1E22);
Here, 1E22 is a primitive double, and you already lost precision by using it.
What you want is
new BigDecimal("10000000000000000000000");
or
new BigDecimal(10).pow(22);

Transformation algorithms for numerical values similar to functionality of Soundex, Metaphone, etc

I'm working on implementing probablistic matching for person record searching. As part of this, I plan to have blocking performed before any scoring is done. Currently, there are a lot of good options for transforming strings so that they can be stored and then searched for, with similar strings matching each other (things like soundex, metaphone, etc).
However, I've struggled to find something similar for purely numeric values. For example, it would be nice to be able to block on a social security number and not have numbers that are off or have transposed digits be removed from the results. 123456789 should have blocking results for 123456780 or 213456789.
Now, there are certainly ways to simply compare two numerical values to determine how similar they are, but what could I do when there are million of numbers in the database? It's obviously impractical to compare them all (and that would certainly invalidate the point of blocking).
What would be nice would be something where those three SSNs above could somehow be transformed into some other value that would be stored. Purely for example, imagine those three numbers ended up as AAABBCCC after this magical transformation. However, something like 987654321 would be ZZZYYYYXX and 123547698 would be AAABCCBC or something like that.
So, my question is, is there a good transformation for numeric values like there exists for alphabetical values? Or, is there some other approach that might make sense (besides some highly complex or low performing SQL or logic)?
The first thing to realize is that social security numbers are basically strings of digits. You really want to treat them like you would strings rather than numbers.
The second thing to realize is that your blocking function maps from a record to a list of strings that identify comparison worthy sets of items.
Here is some Python code to get you started. (I know you asked for Java, but I think the Python is clear and you aren't paying me enough to write it in Java :P ). The basic idea is to take your input record, simulate roughing it up in multiple ways (to get your blocking keys), and then group on by any match on those blocking keys.
import itertools
def transpositions(s):
for pos in range(len(s) - 1):
yield s[:pos] + s[pos + 1] + s[pos] + s[pos + 2:]
def substitutions(s):
for pos in range(len(s)):
yield s[:pos] + '*' + s[pos+1:]
def all_blocks(s):
return itertools.chain([s], transpositions(s), substitutions(s))
def are_blocked_candidates(s1, s2):
return bool(set(all_blocks(s1)) & set(all_blocks(s2)))
assert not are_blocked_candidates('1234', '5555')
assert are_blocked_candidates('1234', '1239')
assert are_blocked_candidates('1234', '2134')
assert not are_blocked_candidates('1234', '1255')

Is there a way to change the internal radix of Java code?

If I want to write a program that deals almost exclusively with, say, base 8 math, is there a way to change the source code or JVM to perform all calculations with this radix without having to explicitly change it on every integer reference?
For example, instead of...
private static final int RADIX = 8;
// ... then, elsewhere ...
System.out.println(Integer.toString(3 + 7, RADIX));
... I could just do ...
System.out.println(3 + 7);
... and have it print the same result of 12? Is there some environment variable or in-code setting I can apply? Or is this simply not possible?
This may seem arcane or a "why in the world would you want to do this" scenario, but if you can imagine having to perform a large number of non-trivial calculations under a different base, then you can see how it would become extremely tedious extremely fast to have to keep manually converting numbers to the appropriate radix.
No, there is no feature like that.
A number is a number no matter what base you're talking about, the radix only comes in when converting to/from strings. If you have to do this all of the time, then create some utility methods that do the work, and always call them. Alternatively, write your own Integer-like class that handles the fromString/toString bit.
public final class OctalInteger extends Number implements Comparable<OctalInteger> {
// Basically a copy of Integer.java, but changes the methods dealing with Strings
}
No.
Also, why would you want that? Imagine how many pieces of code you would break that run in the same JVM - no one coding libraries would expect the default radix to suddenly change.
Your use of a constant is the right way to go.
You can't change default radix. But you can easily write your own print and println procedures which would print integers in octal base.

Follow-up to how to get an Integer as result

I asked a question How to get an Integer as result?
The suggested solution with decimalFormat works, but my problem is that I want my data not only to be presented as ##.0 but to be like this, because in the end of my program I use them. So I want to be exactly in that type; otherwise I get the wrong final number. Any ideas?
EDIT:
let me be more specific. i get 12,344 from my first calc, 14,4566 from my second and 18,5644 from my third.that makes a sum 45.365.Now,if i do then 12,3 , 14,4 and 18,5 the sum is 45.2...thats the point of my answer.i want to have 45.365 at the end and not 45.2
The problem seems to be a design issue with your app.
On the one hand, you want to display the results to the user with 1 digit after the decimal point.
In the other hand, you actually want to keep the extra precision and use it for follow-up calculations.
I would argue that this is a poor user interface model. IMO, the numbers that the user sees should be the numbers that go into the calculations. This means you should either:
show the user more digits after the DP in the first place (or at least give a visual indication that there are more digits), or
do the calculations using the rounded / truncated values ... as displayed to the user.
Once you have figured out a consistent user interface model, the required implementation approach should be much clearer to you.

Categories