(Beginner) - How to I write decimal calc and print results? - java

this is the question.
Write a Java program to declare two integers and demonstrate the use of
addition, subtraction, multiplication, division and modulo operators.
Repeat the calculations from task 1 using decimal numbers.
So I've done part one:
public static void main(String[] args)
{
float a = 4 + 1;
float b = 484 - 48;
float c = 484 * 49;
float d = 32 / 93;
float e = 55 % 787;
System.out.print(a + "\n" + b + "\n" + c + "\n" + d + "\n" + e);
}
but I'm stuck in part two.

Integers are of type int. You are using float and declaring 5 variables. Decimal numbers are type double
public static void main(String[] args)
{
int a = 1;
int b = 2;
int out = a*b;
System.out.print(out);
}
Repeat using doubles
double a = 1.5;
double b = 2.5;

Related

Double variable with 16+ digits gives error: Integer Number too Large

The following code is designed to factorize a number typed into the variable x.
public class testMod{
public static void main(String[]args){
double x = 11868681080091051216000;
StringBuilder output = new StringBuilder("1 * ");
for(double y = 2; y <= x; y++){
while (x % y == 0) {
System.out.print("Calculating... \n");
String printNumber = y + " * ";
x = x / y;
output.append(printNumber);
System.out.print(output.substring(0, output.length() - 2) + "\n");
}
}
}
}
The problem is that the compiler treats 11868681080091051216000 as an int, regardless of the attempt to assign it to a double. As such, it's out of range.
To specify a double literal, you can simply append D to the end – but do note that you'll lose precision this way:
double x = 11868681080091051216000D;
System.out.println(x); // prints 186868108009105E22
If you need the full precision, you can use a BigInteger instead, but you'll still need to specify that number in expressions that Java can handle, such as a product of its factors.

how to convert decimal value in to a Fraction value?

excepted output : 1/4,1/2,3/4,1,5/4,3/2
but my output is coming as in the decimal form . Please help how to print in the form of fraction only.
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(sum+" ");
}
}}
take input in form of string so it will take input in required format and split it by "/" i.e someString.spit("/").
after that make one for loop and take two number and in two different variable store it.
and then take division for both and print it by using "/" in between them.
public class NewClass {
public static void main(String[] args) {
System.out.println(convertype(0.75));
}
public static String convertype(double decimal){
int digitsAfterPoint = String.valueOf(decimal).length() - String.valueOf(decimal).indexOf('.')+1; // get the count of digits after the point // for example 0.75 has two digits
BigInteger numerator = BigInteger.valueOf((long)(decimal*Math.pow(10, digitsAfterPoint))); // multiply 0.75 with 10^2 to get 75
BigInteger denominator = BigInteger.valueOf((long)(Math.pow(10, digitsAfterPoint))); // 10^2 is your denominator
int gcd = numerator.gcd(denominator).intValue(); // calculate the greatest common divisor of numerator and denominator
if (gcd > 1 ){ // gcd(75,100) = 25
return String.valueOf(numerator.intValue()/gcd) +" / " + String.valueOf(denominator.intValue()/gcd); // return 75/25 / 100/25 = 3/4
}
else{
return String.valueOf(numerator) +" / " + String.valueOf(denominator); // if gcd = 1 which means nothing to simplify just return numerator / denominator
}
}
}
Wrote a method where you can convert double numbers to fraction. Use this to convert it and print as below,
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(toFraction(sum)+" ");
}
}
static String toFraction(double x) {
int w = (int) x;
int n = (int) (x * 64) % 64;
int a = n & -n;
return n == 0 ? w+"" : (w * (64 / a) + (n / a)) + "/" + 64 / a;
}
}

Variable-length argument list with "user-defined type" messing up arguments

I've come a long way in the past two weeks since asking my first question, having written a tictactoe game using grid layout and button-pushes to make x and o and declare winner and a class that performs complex number arithmetic (e.g., z1=-3-4i plus z2=7+i via cAdd(z1,z2)) and calculations (e.g., sin(z1) and log(z2)) correctly. (Confirmed by and implemented via help from a CAS called Derive.)
No problem so far.
So I decided to enhance cAdd to accept more than two complex numbers (e.g, cAdd(z1,z2,z3)) and found the following syntax for varying-length argument lists:
public ComplexNumber cAdd ( ComplexNumber ... a);
But whereas the two-parameter version of cAdd(z1,z2) works fine, the "varargs" version (e.g., cAdd(z1,z2,z3)) gives correct results BUT CHANGES THE PARAMETER VALUES so that if z1 is used in a later calculation, it's not what it started out as.
Here's code, followed by output.
class ComplexNumber {
double real, imag;
public ComplexNumber() { // default constructor
}
public ComplexNumber(double a, double b) { // initializer constructor
real = a;
imag = b;
}
public class CBug {
public static void cPrint(String s, ComplexNumber z) {
System.out.println(s + z.real + " + " + z.imag + "i");
}
public static void dump(int n, ComplexNumber z, ComplexNumber [] a){
System.out.print("Dump " + n + "; sum so far is " );
cPrint("z = ", z);
for (int i = 0; i < a.length; i++)
cPrint("" + i + ": " ,a[i]);
System.out.println("");
}
public static ComplexNumber cAdd(ComplexNumber ... a) {
ComplexNumber z = a[0];
for (int i = 1; i < a.length; i++){
dump(i,z,a);
z.real = z.real + a[i].real;
z.imag = z.imag + a[i].imag;
}
dump(99,z,a);
return z;
}
public static void main(String[] args) {
ComplexNumber sum = new ComplexNumber();
ComplexNumber z1 = new ComplexNumber(1000,500);
ComplexNumber z2 = new ComplexNumber(7, 1);
ComplexNumber z3 = new ComplexNumber(100,100);
cPrint("z1 = ", z1);
cPrint("z2 = ", z2);
cPrint("z3 = ", z3);
System.out.println("");
System.out.println("++++++++++++++++++++++");
sum = cAdd(z1, z2, z3) ;
cPrint ("z1 + z2 + z3 = " , sum);
System.out.println("--------------------");
cPrint("z1 = ", z1);
cPrint("z2 = ", z2);
cPrint("z3 = ", z3);
}
}
Output:
run:
z1 = 1000.0 + 500.0i
z2 = 7.0 + 1.0i
z3 = 100.0 + 100.0i
++++++++++++++++++++++
Dump 1; sum so far is z = 1000.0 + 500.0i [correct]
0: 1000.0 + 500.0i
1: 7.0 + 1.0i
2: 100.0 + 100.0i
Dump 2; sum so far is z = 1007.0 + 501.0i [correct]
0: 1007.0 + 501.0i [but WHY DID ARG[0] CHANGE to "z so far"?]
1: 7.0 + 1.0i
2: 100.0 + 100.0i
Dump 99; sum so far is z = 1107.0 + 601.0i [correct]
0: 1107.0 + 601.0i [WHY DID ARG[0] CHANGE AGAIN to new "z so far"?]
1: 7.0 + 1.0i
2: 100.0 + 100.0i
z1 + z2 + z3 = 1107.0 + 601.0i [correct]
--------------------
z1 = 1107.0 + 601.0i [WHY DID z1 (a.k.a. arg[0]) CHANGE?]
z2 = 7.0 + 1.0i
z3 = 100.0 + 100.0i
BUILD SUCCESSFUL (total time: 0 seconds)
Can't use 1st parameter in subsequent calculations since cAdd damaged it.
=============================
Here's what I now have for cAdd (since my original "fix" [described in comments below] was a bit wacko]:
public static ComplexNumber cAdd(ComplexNumber ... a) {
ComplexNumber z = new ComplexNumber();
for (int i = 0; i < a.length; i++){
z.real += a[i].real;
z.imag += a[i].imag;
}
return z;
}
===============================
When you create your variable z in cAdd, you refer it to a[0]. Now both z and a[0] refer to the same object. Then you change it.
What you should do is make a copy of the first element for z, so that when you modify z, you don't modify a[0]. Something like this:
ComplexNumber z = new ComplexNumber(a[0].real, a[0].imag);

quadratic formula with scanner inputs

Okay so I am a complete Java noob, and I'm trying to create a program for class that runs a quadratic equation using scanner inputs. So far what I've got is this:
import java.util.*;
public class QuadraticFormulaSCN {
public static void main(String[]args) {
System.out.println("insert value for a:");
Scanner scan1 = new Scanner(System.in);
double a = scan1.nextDouble();
System.out.println("insert value for b:");
Scanner scan2 = new Scanner(System.in);
double b = scan2.nextDouble();
System.out.println("insert value for C:");
Scanner scan3 = new Scanner(System.in);
double c = scan3.nextDouble();
double answer =((Math.sqrt(Math.pow(b,2)-(4*a*c))-b)/2);
double final2 =(-b + Math.sqrt(Math.pow(b,2)-(4*a*c)))/2;
System.out.println("The x values are:" + answer + final2);
}
}
But I get a weird output, specifically NaNaN... What do I do to fix this? What am I doing wrong?
I'm a little late to answer, but I corrected your problems (described in the other answers), fixed one of your calculations, and cleaned up your code.
import java.util.*;
public class Test {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Insert value for a: ");
double a = Double.parseDouble(s.nextLine());
System.out.println("Insert value for b: ");
double b = Double.parseDouble(s.nextLine());
System.out.println("Insert value for c: ");
double c = Double.parseDouble(s.nextLine());
s.close();
double answer1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
double answer2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
if (Double.isNaN(answer1) || Double.isNaN(answer2))
{
System.out.println("Answer contains imaginary numbers");
} else System.out.println("The values are: " + answer1 + ", " + answer2);
}
}
NaN is something you get when the calculation is invalid. Such as dividing by 0 or taking the squareroot of -1.
When I test your code with a = 1, b = 0 and c = -4 the answers is 2.02.0
The formatting is not right and the calculation of final2 is not negated.
Otherwise the code is right.
To improve you could check whether the discriminant is negative.
double d = b*b -4 * a * c;
if (d < 0){
System.out.println("Discriminant < 0, no real solutions" );
return;
}
double x1 = (-b -sqrt(d))/(2*a);
double x2 = (-b +sqrt(d))/(2*a);
System.out.format("The roots of your quadratic formula are %5.3f and %5.3f\n",x1,x2);
Or, if you prefer support for solutions from the complex domain:
if (d < 0) {
System.out.println("Discriminant < 0, only imaginary solutions");
double r = -b / (2 * a);
double i1 = -sqrt(-d) / (2 / a);
double i2 = sqrt(-d) / (2 / a);
System.out.format("The roots of your quadratic formula are (%5.3f + %5.3fi) and (%5.3f + %5.3fi)\n",r, i1, r, i2);
return;
}
You are getting NaN because you are attempting to take the square root of a negative number. In math that's not allowed unless you are allowing complex numbers, e.g. 1 +/- 2i.
This can happen in quadratic formulas when the discriminant (the thing in the square root) is negative, e.g. x^2 + 6*x + 100: b^2 - 4ac = 36 - 400 = -364. Taking the square root of a negative number in Java leads to NaN. (not a number)
To test for NaN, use Double.isNaN and handle the NaN appropriately.
In addition, your calculations are incorrect even if NaN isn't being encountered:
$ java QuadraticFormulaSCN
insert value for a:
1
insert value for b:
5
insert value for C:
6
The x values are:-2.0-2.0
This should have outputted 2.0 and 3.0
You should only do the calculation when
discriminant is equal or greater than zero
if(((Math.pow(b,2)-(4*a*c))>= 0){ /* Calculation here */ }
else {/*error message or complex number calculus*/};
One thing I always try to do is put all my math in appropriate parenthesis to avoid an, all too easy, Order of Operations mistake. The NaN is saying "Not a number." You would also get that message if the user input numbers that could not produce a result, such as a trying to get the square root of a negative number. Also, just as a note, you can save sometime by only using on Scanner for a,b, and c.
public class QuadraticFormula{
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
double quadPos = (-b + Math.sqrt(Math.pow(b,2)-(4*a*c)))/(2*a);
double quadNeg = (-b - Math.sqrt(Math.pow(b,2)-(4*a*c)))/(2*a);
System.out.println("-b - = " + quadNeg + "\n-b + = " + quadPos);
}
}

help for a java assignment

I have created a method to create some random double values for example 10 values : num1, num2, …num10 which sum of this 10 values is 1 : num1+num2+…+num10 = 1
My method is like the method in forum
Getting N random numbers that the sum is M :
private static double[] randSum(int n, double m) {
Random rand = new Random();
double randNums[] = new double[n], sum = 0;
for (int i = 0; i < randNums.length; i++) {
randNums[i] = rand.nextDouble();
sum += randNums[i];
}
for (int i = 0; i < randNums.length; i++) {
randNums[i] /= sum * m;
}
return randNums;
}
But this method create very long numbers like: 0.18593711849349975
I even used Math.round() method but with this method my numbers are 0.0, 0.5, 0.0 , …
I need numbers from 0.01 to 0.99 or 0.1 to 0.9. If I was using integer numbers I could do this with something like Random.nextInt(0.98) +0.01 , but nextDouble() method doesn’t accept parameters, how can I do this? Would you please help me? thanks
You could generate integers via nextInt, and then divide them by the required power of 10.
Generate nextDouble(); and round it using this method
public static double round(double d, int decimalPlace){
BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
double d = 3.1537;
// output is 3.2
System.out.println(d + " : " + round(d, 1));
// output is 3.15
System.out.println(d + " : " + round(d, 2));
// output is 3.154
System.out.println(d + " : " + round(d, 3));
Source
Multiply your number by 100 and round the result. That will give you the original number with the insignificant digits stripped off. Then subsequently divide the result by 100 to get back to the original scale.
x = Math.round(x*100.0) / 100.0;
If you want to use 2 decimals, you could do it as follows:
private static double[] randSum(int n, double m){
double[] randoms = new double[n];
int valueLeft = (int) (m * 100);
for(int i = 0; i < n-1; i++){
int tempRand = (int)(Math.random() * valueLeft);
randoms[i] = (double)tempRand / 100;
valueLeft -= tempRand;
System.out.println(tempRand + " " + randoms[i] + " " + valueLeft);
}
randoms[n-1] = (double)valueLeft/100;
return randoms;
}

Categories