How to write a maths expression in terms of x in Java - java

I am trying to write a function that parses in 2 numbers e.g. coefficient 5 and power 3. I want the output response to be 5x^3.
public void Variable(double c, double p)
{
coefficient = c;
power = p;
}
public Expression derive()
{
System.out.print("Youre term is " + coefficient + "" + Math.pow("x",power));
}
What have I done wrong here? It's not accepting my "x" in the pow function. But I'm not sure how to have a simple letter in there?
Cheers

Math.pow(double a, double b) doesn't accept a string as its first argument. It expects a double for both the base and the exponent. That method is for calculating values based on the base and the exponent supplied.
-> Returns the value of the first argument raised to the power of the second argument.
Instead, what you want to achieve can easily be done without using pow() method.
Just display coefficient + "x ^ " + power to the console.
System.out.print("Your term is " + coefficient + "x^" + power);

Related

Divide A number per 5, getting the weight ratio and using it to split another number [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
An example will clear the idea:
number A = 12
number B = 20
I need to divide A per 5 until I dont go less than 5. So I get 3 parts: 5,5 an 2.
Now I have to use this result to split B given the weight just calculated.
So 20 * (5/12), 20 * (5/12), 20* (2/12) and their sum of course must be exactly equal to B (20 in our case)
I have to do this without losing any precision and trying to have the result as much correct as possible. My example is using int, but I need to do that with decimals as well.(A could be 12.37 and B could be 20.13 for instance) Anyone knows a library or a hint to do that ?
Well, this question (at least the way I understand it) is pretty simple to solve:
What we've got: A and B, which may be decimal
What we want: a sequence (a1, a2, ..., an) with the following properties:
any element of the sequence is smaller equal 5
all elements sum up to A: a1 + a2 + ... + an = A
a1 / A * B + a2 / A * B + ... + an / A * B = B
Well time for a bit of math:
B = //RHS => LHS
a1 / A * B + a2 / A * B + ... + an / A * B = //factorize
(a1 + a2 + ... + an) / A * B = //(a1 + a2 + ... + an) = A
B
Or in other words: use whatever sequence you like. As long as the elements of the sequence sum up to A and are all smaller-equal to B you're fine.
As for the precision:
Using the type of the input there shouldn't be any issue with precision, as the output can be built in a manner to only consist of integers and the decimal part of the input (so actually your output might have a better -unused - precision than the input).
So to generate the values a1 / A * B, a2 / A * B, ... we need to do the following:
Use BigDecimal for maximum-precision - beware though, as B / A may be periodic! The rest works just the usual way, except that you need to use methods instead of normal operators:
a + b with BigDecimal would be a.add(b)
a * b with BigDecimal would be a.multiply(b)
...
You can look up the details in the documentation.
after reading your question, i cant figure out what is that you want.
Do you want the sequence of 5,5,5,..n(where n<5) for A or B,and also the thing about sum for B is it a condition or is that what you are trying to achieve ?
anyway if its the sequence that you want then you could do this :
int A,B; //if A=12
int numOfFives=A/5; // then numOfFives=2
int remainder=A%5; //then remainder=2
using this method will ensure that the last number will always be less than one.
so you could do the sum like :
sum=0;
for(int i=0;i<numOfFives;i++){
sum+=B*(5d/12d); // 5/12 with sum as int gives result sum =0 , so change the fraction part accordingly to your need.
}
sum+=B*(remainder/12d);
if you want the sequence then do :
System.out.println("Sequence = ");
for(int i=0;i<numOfFives;i++){
System.out.println(5+",");
}
System.out.println(remainder);
also make your calulation of sequence much easier.
Edit 1
here is the Live Program on IdeOne if you want to check it out.
inputs :
A=12
B=20
outputs:
Final Sum=20.0
Sequence=5,5,2
Try out this example:
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Example {
public static void main (String[]args) {
BigDecimal a = new BigDecimal("16.3");
BigDecimal b = new BigDecimal("20");
BigDecimal[] div_rem = a.divideAndRemainder(new BigDecimal("5"));
String s = "";
for (int i = 0; i<div_rem[0].intValue();i++){
s += b +" * (5/"+a+"), ";
}
s += b +" * ("+div_rem[1]+"/"+a+")";
System.out.println(s);
System.out.println(b +" * (5/"+a+") = " + b.multiply(new BigDecimal("5").divide(a, 5,RoundingMode.HALF_UP)));
System.out.println(b +" * ("+div_rem[1]+"/"+a+") = " + b.multiply(div_rem[1].divide(a,5 ,RoundingMode.HALF_UP)));
}
}

Modulus not returning the correct value for a non-negative input

I am working on a scaled down RSA encryption and decryption methods and everything seems to be working well, until I try to take the modulus of a number. The modulus operator isn't returning the expected result.
for(int k = 0; k < sA.length; k++){
int value = Integer.parseInt(sA[k]);
System.out.println("value : " + value);
double mToE = Math.pow(value,e);
System.out.println("mToE: " + mToE);
double c = mToE % n;
System.out.println("C: " + c);
sA is an array containing the values {06707708, 30670320, 50050050}.
mToE represents M(in this case each string in sA) raised to the power of e(13).
C = M^e mod n where n is input as a parameter.
These specific lines output:
value : 6707708
mToE: 5.56498415666044E88
C: 5.2630797E7
0
value : 30670320
mToE: 2.1248975415575414E97
C: 8.973537E7
1
value : 50050050
mToE: 1.2366838911816623E100
C: 3.4150233E7
2
For example the first value of c should be:
c: 3.2059734E7
or 32059734
What reason could there be for getting this result?
Thanks in advance for all of your advice.
The double type has lots of precision, 53 bits, but that's not enough to store values as precise as unity at the very high values you're seeing. The values of mToE are the double values that are closest to the true values of calculation.
With the Math.ulp method (unit in last place), we can determine the precision of a double value of the magnitude 5.56498415666044E88.
System.out.println(Math.ulp(mToE));
This outputs
7.067388259113537E72
Because of this, your value is very likely to be off in 72 digits. This will of course completely mess up the value of c, which is taken from a mod % operation.
For the necessary precision, you will need to use BigIntegers. Also, BigInteger has its own modPow method built specifically for your purpose.

Recursively parse a string of ones and zeroes into its decimal value

My goal is to get a String of ones and zeroes from input, then use the bin2Dec method to parse that binary string into a decimal number. How can I convert this correctly?
Here is what I have so far:
public class Tester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a binary number string: ");
String s = input.nextLine();
System.out.println("The decimal value is " + bin2Dec(s));
}
public static int bin2Dec(String binaryString){
}
}
The algorithm to do this is actually pretty simple.
If you look at a binary string, say, "10110" (22), what you'll notice is that equals 16 + 4 + 2. Look at this a bit harder, and you'll see it corresponds to 1 * 2^4 + 0 * 2^3 + 1 * 2^2 + 1 * 2^1 + 0 * 2^0. See the pattern? For each digit with value v and position n, it's "contribution" to the total sum is v * 2^n.
Now, this problem is actually easier to do iteratively (With a for-loop), but I assume this is a homework question and therefore you have to do it recursively.
You'll need to make another method, public static int bin2dec(String bin, int position) (this is called overloading the method, two methods can have the same name as long as their signatures are different). In this new method, you can follow the algorithm outlined above:
If position equals bin.length(), you've gone past the end of the string. Just return 0.
Otherwise, set v equal to the integer value of the character at position (You can either use the integer parse method, or just an if/ternary because there are only two options).
Multiply v by 2^position (hint: Math.pow).
Return v plus bin2dec(bin, position + 1) (this is the actual recursive part).
Now, in the original bin2dec, you can just put return bin2dec(bin, 0). That just allows you to call bin2dec without initializing the recursive counter, which is just general bookkeeping that callers don't want to deal with (not so important here, but very important in larger projects).
public static String showAsBinString(int n, String s){
if(n > 1){
s = showAsBinString(n/2, s);
}
s += n%2 == 0 ? "0" : "1";
return s;
}
System.out.println(showAsBinString(45, ""));
101101

Why is it adding the variables wrong?

I'm using Java but, it's not adding the amount correctly. I'll give my parts of my code.
final double taxrate=.08;
Map<String,Integer> Priceproduct= new HashMap<String,Integer>();
Priceproduct.put("shoes",(int) 50.00);
Priceproduct.put("shirts",(int) 30.00);
Priceproduct.put("shorts",(int) 75.00);
Priceproduct.put("caps",(int) 15.00);
Priceproduct.put("jackets",(int) 100.00);
System.out.print("\n Enter the product: ");
String product=keyboard.nextLine();
System.out.print( "\n Enter the quantity of the product");
int quantity=keyboard.nextInt();
int cost= Priceproduct.get(product)*quantity;
int tax= (int) (cost*taxrate);
System.out.print("\n tax=" +cost*taxrate+"");
int TotalBill= cost+tax;
System.out.print("\nTotal="+cost+ + +tax+"");
When it adds the cost and tax (those two are correct) it's gets the completely wrong answer.
For example 3 shirts= 90, the tax equals 7.2, and the total becomes 907.
Do I need to use DecimalFormat or something else?
Change this:
System.out.print("\nTotal="+cost+ + +tax+"");
to this:
System.out.println();
System.out.print("Total=" + (cost + tax));
(The problem is that + is left-associative, so without parentheses around your addition, "a" + b + c means ("a" + b) + c, which does string-concatenation at both stages.)
When you perform an operation alongside a string Java will perform that operation as if the operands were strings.
In your System.out.println() calls you don't need to redo the calculations, just print out the variables "tax" and "totalBill". (This will solve the problem of printing '907')
You will only ever get integer values because you are using int type for everything. If you want to have decimals to indicate cents you should be using type double.

Return a double with only two decimals in Java as part of a larger string?

As part of a larger program, I have this function that, when called, returns the string under return. accountHolder, balance, interestRate, and points are variables in an object of type RewardsCreditAccount. So, for example, I declare an object here:
RewardsCreditAccount testAccount = new RewardsCreditAccount("Joe F. Pyne", 7384.282343837483298347, 0.173, 567);
So this object will set accountHolder = "Joe F. Pyne", balance = 7384.282343837483298347, and so on.
In the function below, I return this information in a string that should look like this:
Joe F. Pyne, $7384.282, 17.28%, 567 points
Using this function:
public String toString() {
return (accountHolder + ", $" + + balance + 100*interestRate + "%, " + points + " points");
}
However, it is in fact returning this:
Joe F. Pyne, $7384.282, 17.299999999999997%, 567 points
I tried this, but to no avail
public String toString() {
return (accountHolder + ", $" + + ("%,1.2f",balance) + 100*interestRate + "%, " + points + " points");
}
This is rather annoying, because I want it to only return two decimal places. I know this can be done using %1.2f, but I have no idea how to format the syntax for that. I would vastly appreciate any help on getting the decimal value to display properly. Thanks!
You'll have to use String.format(); with that format-String.
So this
public String toString() {
return (accountHolder + ", $" + + ("%,1.2f",balance) + 100*interestRate + "%, " + points + " points");
}
Should be:
public String toString() {
return String.format("%s, $%,1.2f %s%%, %s points", accountHolder, balance, 100*interestRate, points );
}
With the formatters set so that it is printed according to your desires.
Use DecimalFormater for formatting your value.
new DecimalFormat("###.##").format(17.299999999999997);
For reference.
You will need to use String.format() to format your returned String: -
String.format("%5.2f",balance)
Floating point numbers are not always easy to deal with.
Your problem lies in the fact that floating point types (as float and double, and their boxed counterparts) are just binary approximations of their decimal representation, so all kinds of such problems can arise when not taking this into count.
You also have to pay attention when handling very large values, because it can occur that (a== (a+1))==true...
Also, for currencies, and other such critical data, I'd recommend BigDecimal, which stores the exact string representation, not the binary approximation. That is not the most trivial thin on Earth to handle though, but given the criticality of data, I think it is unavoidable.

Categories

Resources