I have some inputs say x1,x2,x3. I have to multiply each input with some weight and add them. Like alpha * x1 + beta * x2 + gamma * x3.
Range of x1,x2,x3 is 0 to 1.
Range of weights is also 0 to 1.
I want some algorithm to give more weight to higher values and less weight to lower values.
Like if x1 has higher value among three then 60% weight age can be given to x1.
x2 has 2nd highest value 30% to it and 20% to last value completing 100%.
What I have tried so far is given below but values are static, I am giving weight 0.6 to highest value the 0.3 and 0.2 respectively. Is there any way to give weight dynamically according to value of input?
if (x1>x2 and x1>x3 ) {
if (x2>x3) {
sum= 0.6*x1 + 0.3*x2 + 0.2*x3;
}
if (x3>x2) {
sum= 0.6*x1 + 0.2*x2 + 0.3*x3;
}
}
if (x2>x3 and x2>x1 ) {
if (x1>x3) {
sum= 0.3*x1 + 0.6*x2 + 0.2*x3;
}
if (x3>x1) {
sum= 0.2*x1 + 0.6*x2 + 0.3*x3;
}
}
if (x3>x2 and x3>x1 ) {
if (x2>x1) {
sum= 0.2*x1 + 0.3*x2 + 0.6*x3;
}
if (x1>x2) {
sum= 0.3*x1 + 0.2*x2 + 0.6*x3;
}
}
You're saying but values are static.
If by that you mean that you hardcoded values like:
double x1 = 1.0;
double x2 = 2.0;
double x3 = 3.0;
then the solution is to get them by user input:
Scanner scanner = new Scanner(System.in);
System.out.print("x1=");
double x1 = scanner.nextDouble();
System.out.print("x2=");
double x2 = scanner.nextDouble();
System.out.print("x3=");
double x3 = scanner.nextDouble();
scanner.close();
Then you make all the calculations.
Related
I'm writing a program that will calculate the BMI of a person. Here's the assignment that I was given:
"Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters. Write a program that prompts the user to enter a weight W in pounds and height H in inches and displays the BMI. Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters."
Input: (Line 1) Real number within 50 to 200
(Line 2) Real number within 10 to 100
Output: BMI value (Floating point should only be printed until the second decimal point)
The problem is that whenever I use "System.out.printf("%.2f\n", BMI)", the output is rounded up rather than cutting off the rest of the decimal point. Here's my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double weight = input.nextDouble();
double height = input.nextDouble();
double weightKG;
double heightM;
double heightMSquare;
double BMI;
final double kilogram = 0.45359237;
final double meter = 0.0254;
while ((weight > 200) || (weight < 50)) // Error catching code.
{
weight = input.nextDouble();
}
while ((height > 100) || (height < 10))
{
height = input.nextDouble();
}
weightKG = weight * kilogram; // Convert pounds and inches to
kilograms and meters.
heightM = height * meter;
heightMSquare = Math.pow(heightM, 2); // Compute square of height in
meters.
BMI = weightKG / heightMSquare; // Calculate BMI by dividing weight
by height.
System.out.printf("%.2f\n", BMI);
}
}
Here is a method I wrote that solves this with regexes and string manipulation.
private static String format2Dp(double x) {
String d = Double.toString(x);
Matcher m = Pattern.compile("\\.(\\d+)").matcher(d);
if (!m.find()) {
return d;
}
String decimalPart = m.group(1);
if (decimalPart.length() == 1) {
return d.replaceAll("\\.(\\d+)", "." + decimalPart + "0");
}
return d.replaceAll("\\.(\\d+)", "." + decimalPart.substring(0, 2));
}
What I did was turning the double to a string, extract the decimal part out of it and substringing the decimal part. If the decimal part is only 1 character long, add a zero to the end.
This method works with numbers expressed in scientific notation as well.
So here is my task:
A postal company for a package charges $15 for the first
pound or a fraction thereof and $10 per pound for anything over one
pound. Write a program that prints the charge of a package.
Variables:
weight
First execution:
Weight? -12 Weight must be a positive number.
Second Execution:
Weight? 0 Weight must be a positive number.
Third Execution:
Weight? 2 Pay: $25.00
Forth Execution:
Weight? 2.8 Pay: $33.00
Fifth Execution:
Weight? 2.07 Pay: $25.70
and Here is the code I have developed so far:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else if (weight == 1) {
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
} else {
for (double i = 1; i < weight; i = i + .01) {
if (weight > 1) {
output = output + (1 / 10.00);
}
}
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
}
}
Everything works, but what I can't figure out is why (especially in the Fourth and Fifth Execution) is the final output always .10 cents off. Can anyone help me get to the accuracy I need?
Here is what I came up with:
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else {
// Print the charge of the package
if (weight > 1) {
output = cost + ((weight-1) * 10);
} else {
output = cost;
}
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
This should handle all of your cases, as well as numbers between 0 and 1 assuming it's $1 per 0.1 lbs. Instead of your for-loop, you can just use the cost + ((weight-1) * 10) formula. I removed the check to see if weight was equal to 1 because it's handled in the else clause.
If I understand the question correctly, you should never have any fractional dollar amount because anything over a pound is automatically rounded up to the next pound. ie: 2.01 lbs would become 3 lbs. If this is correct, then you could use Math's ceil function to round the weight up to the nearest whole pound, then do something like this:
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else if (weight == 1) {
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
} else {
double temp = (Math.ceil(weight)) - 1;
for(double i = temp; i > 0; i-- ) {
output += 10;
}
output += cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
}
}
This way, you don't need to bother with 10 cent increments. I hope this helps. Let me know if you have any questions.
This: double i = 1; i < weight; i = i + .01 could be your problem.
Doubles are not exact for decimal math. You're expecting i == weight, at which point the loop should stop, but it might not because i + .01 (however many times) is a tiny fraction less than weight.
My advice is to ditch the loop. If the package is over 1 lb, just subtract one pound from the weight, multiply by the $10 per pound, and then round to the two decimal places you need (NOTE: round it according to how it's spec'd to be rounded, don't just let the conversion from double to decimal do it on its own. There are multiple ways to round something, and decimal does not magically know which one is right for your problem.)
EDIT: Look at your solution, is it supposed to only work to a resolution of 1/10 of a lb? If so, start by rounding the weight. Again, round it according to how it needs to be rounded (down, up, or nearest).
I want to make sure that initializationg of the float variable resultd is correct. Since it is where the error lies.
static void caculateValues() {
int a, b;
int resulta, results, resultm;
float resultd;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a:");
a = sc.nextInt();
System.out.print("Enter b:");
b = sc.nextInt();
{
//This is the only part I edited//
resulta= a+b;
results=a-b;
resultm= a * b;
resultd= a / b;
//This is where I stopped editing//
}
System.out.println("The result of adding is " + resulta);
System.out.println("The result of subtracting is " + results);
System.out.println("The result of multiplying is " + resultm);
System.out.println("The result of dividing is " + resultd);
}
They claim my output should looks something like this:
(a = -50) (b = -20)
The result of adding is -70
The result of subtracting is -30
The result of multiplying is 1000
The result of dividing is 2.5
But supposedly my input shows:
The result of adding is -70
The result of subtracting is -30
The result of multiplying is 1000
The result of dividing is 2.0
Even if resultd is a float, you are still dividing two ints:
a / b
In Java, division of 2 ints must be an int. That is why 2.0 is showing up. -50 / -20 is 2, not 2.5 in Java. Only after the 2 is generated is it promoted to a float upon assignment to resultd.
Cast one of the variables to a float to force floating-point math from the start.
resultd = (float) a / b;
You could just as easily make resultd a double and cast a to a double instead.
int single = 0, doub=0, triple=0, homer=0, atbats=0, totalbase, totalhits;
double slug, battingavg;
Scanner sc = new Scanner(System.in);
System.out.print("Enter singles (-1 to end): ");
single = sc.nextInt();
while (single != -1)
{
System.out.print("Enter doubles: ");
doub = sc.nextInt();
System.out.print("Enter triples: ");
triple = sc.nextInt();
System.out.print("Enter home runs: ");
homer = sc.nextInt();
System.out.print("Enter total at bats: ");
atbats = sc.nextInt();
System.out.print("Enter the player's name: ");
String name = sc.next();
totalbase = (single + doub * 2 + triple * 3 + homer * 4);
slug = totalbase / atbats;
battingavg = (single + doub + triple + homer) / atbats;
System.out.println("Player's name is " + name);
System.out.printf("The slugging percentage is %.3f\n", + slug);
System.out.printf("The batting percentage is %.3f\n", + battingavg);
System.out.print("Enter singles (-1 to end): ");
single = sc.nextInt();
}
This program will only output a 1 or a 0 after the calculations. Everything else works fine, but It just doesn't seem to do the calculations.
The problem is that when you do integer divisions, you'll get integer values. Instead use double or float data types. I see slug and battingavg are already doubles, but you're assigning the result of an integer division to them. If you cast at least one of the values in your calculations to a double you should get the output you expect. Example:
slug = totalbase / (double) atbats;
battingavg = (single + doub + triple + homer) / (double) atbats;
When you divide integer values and store the result in a double that is a widening conversion, but the value was calculate as an integer and thus you're widening the integer value.
Change this,
slug = totalbase / atbats;
battingavg = (single + doub + triple + homer) / atbats;
to something like this,
slug = ((double) totalbase / atbats);
battingavg = ((double) (single + doub + triple + homer) / atbats);
to get double values into your double variables.
I want to make a program that uses the Babylonian algorithm to compute the square root of a positive number n as follows :
Make a guess at the answer (you can pick n/2 as your initial guess).
Compute r = n / guess.
Set guess = (guess + r) / 2
Go back to step 2 until the last two guess values are within 1% of each other.
Now that's my code.
double n = input.nextDouble();
double guess = n / 2;
while ()
{
double r = n / guess;
guess = (guess + r) / 2;
System.out.println(guess);
}
How can I get the loop to stop iterating when guess is within 1% of the previous guess ? I don't get the part "guess is within 1% of the previous guess".
This should do the trick:
double n = input.nextDouble();
double guess = n / 2;
double pctDiff = Double.MAX_VALUE;
double lastGuess = guess;
while (Math.abs(pctDiff) >= 0.01)
{
double r = n / guess;
guess = (guess + r) / 2;
pctDiff = ((guess-lastGuess)/lastGuess); // normally, multiply by 100, but don't need to necessarily...
lastGuess = guess;
System.out.println(guess);
}
Store the previous and the current guesses in separate variables. Then simply have an if statement to check how far your currentGuess is from previousGuess.
The algorithm listed in the book Algorithms for square root with explanation
added is
public static double sqrt(double c)
{
if (c < 0) return Double.NaN;// less than zero are complex numbers
double err = 1e-15; // (1 power -15)decreasing this will cause more accuracy
// and more iterations to converge(quadratic
// convergence) toward the actual value
double t = c; // initial positive value
while (Math.abs(t - c/t) > err * t)
t = (c/t + t) / 2.0;
return t;
}