My task is to write a program which prompts the user to enter a positive double a and an integer
n greater than 2, and print the value of the nth root of positive integer a to the screen with accuracy to 100 places. I've used Math.pow to be able to get the root, and I feel as though I've done everything right. The only problem is that every time I run my program, the output is 1.0, no matter what numbers I input for a and n. What is the problem with my code?
import java.util.Scanner;
import java.lang.Math;
public class Q8 {
public static void main(String[] args) {
System.out.println("Enter a positive number: ");
Scanner in = new Scanner(System.in);
double a = in.nextDouble();
System.out.println("Enter an integer greater than 2: ");
Scanner in2 = new Scanner(System.in);
int n = in.nextInt();
System.out.println(pow (a,n));
}
private static double pow(double a, int n) {
if (n == 0){
return 1;
}
else{
double sum = Math.pow(a,(1/n));
return sum;
}
Why is the answer always 1.0?
Replace 1/n with 1.0/n.
You're getting integer division, so no matter what n is, if it's 2 or higher, then 1/n is coming out zero. Then you're raising your number to the zeroeth power, which gives 1.
Replacing 1 with 1.0 makes the division into a floating point division - that is, the result won't be truncated to an integer. This is what you want.
First of all, I'm assuming that
double sum = Math.pow(a,(1/root));
should be
double sum = Math.pow(a,(1/n));
since there is no root variable in your code.
Second of all, 1/n would give you 0 for every integer n > 1. Therefore sum would be 1.0.
You should replace it with :
double sum = Math.pow(a,(1.0/n));
or
double sum = Math.pow(a,(1/(double)n));
In order to get a division of double variables.
Related
I wrote a method that calculates the combination of 2 numbers and it works for smaller numbers where n = 10 and r = 3, but when input n as 100 and r as 3 it throws an arithmetic exception
" / by zero"
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter n: ");
int n = scan.nextInt();
System.out.print("\nEnter r: ");
int r = scan.nextInt();
scan.close();
int ans = factorial(n) / (factorial((n-r)) * factorial(r));
System.out.print("\nThe combination is: "+ans);
}
static int factorial(int num) {
for(int i = num; i>1; --i) {
num *= (i - 1);
}
return num;
}
}
but i don't know what the problem is. it works for smaller numbers of n.
You're multiplying values which result in a number too big to fit inside an integer.
If you print out the num inside your for loop, you'll notice it eventually either goes negative or to zero. This is due to overflow.
For your example of n=100 and r=3 not even long will do. You'll need to use something like BigInteger.
Keep in mind that using BigInteger will drastically slow down your program when compared to using primitives.
If you're not interested in having such large numbers and were just curious why it wasn't working, you can also use Math.multiplyExact(int x, int y) or Math.multiplyExact(long x, long y) if you're using Java 8 or above.
By using these methods, you'll avoid having to deal with the side-effects of overflow since they will throw an ArithmeticException if the result overflows.
Change the data type of num from int to double
So i was calculating e(third row in picture) with numerical methods.
I was increasing the number of elements i used every iteration. And when i executed the program, floating point variable behaved in a way i didn't understand. Here is the program and the result.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int factorial = 1;
int counter = 0;
int iterationNumber;
double total = 0;
int tempCounter;
System.out.print("Enter iteration number: ");
iterationNumber = input.nextInt();
while (counter <= iterationNumber) {
tempCounter = counter;
while ((tempCounter - 1) > 0) {
factorial *= tempCounter;
tempCounter--;
}
total += ((double)1 / factorial);
System.out.println(total);
factorial = 1;
counter ++;
}
}
}
So my question is why does the value of e starts to decrease after a while instead of increasing? I want to learn how floating point variable behaves during this program and the logic behind it.
Another question is why does it start to say infinity?
n! quickly exceeds Integer.MAX_VALUE and overflows to a negative number. You are then adding a negative number to your total --- thus the decrease.
You can use BigDecimal for your calcualtions. It is slower, but will do the job.
package Review_Randomnum;
import java.util.Scanner;
public class RandomNum {
public static void main(String[] args) {
System.out.println("Please enter a minimum value: ");
Scanner input = new Scanner(System.in);
int first = input.nextInt();
System.out.println("Please enter a maximum value: ");
int second = input.nextInt();
int number = ((int)(Math.random()) * ((second - first)) + first);
System.out.println(number);
}
}
So I've checked numerous answers on this website, and to no avail, I don't get any errors, I just get the minimum value printed. I don't know how to get the program to produce a random integer between the two values input
Your random number is being truncated to 0 in the following expression:
((int)(Math.random())
The reason for this is that Math.random() returns a double greater than or equal to 0 and less than 1, which when cast to an int will be truncated to 0 (see the documentation for more information).
Instead, compute your desired number first as a double, and then cast back to an int:
int number = (int)(Math.random() *(second - first) + first);
//java program that asks the user to input a number that e^x=1+x+x^2/2! +x^3/3!... e is a mathematical constant equal to 2.718...
import java.util.Scanner;
public class taylor_2 {
public static void main(String args[]) {
Scanner input=new Scanner(System.in);
double x; //input for x
double factorial=1; //initializes factorial
int counter=1; //initializes counter
double result=1; //initializes result
System.out.println("Enter non negative number"); //asks user to enter x
x=input.nextInt();
//output in while loop will continue to be generated if user doesn't entered a negative number
while(x<1){
System.out.println("I said entered a positive number");
x=input.nextInt();
}
while(x>counter){
factorial=factorial*counter;//factorial formula
result=result+(Math.pow(x,counter))/factorial; //equation for e^x=1+x+x^2/2! +x^3/3!
counter++;
}
System.out.println("Taylor series is " +result);//output for taylor equation e^x
}
}
Here is the output of my code:
Enter non negative number
2
Taylor series is 4.0
When I entered 2 , it should have outputted 7.3890560983 instead of 4.0 since e=2.718... and e^2=7.3890560983. What am I doing wrong?
The problem is that the Taylor series is not the same function that e^x.
It will return a function that is close to the function e^x.
For understanding it better, I recommend you to look the second picture of the next link:
https://en.wikipedia.org/wiki/Taylor_series
You can see in the previous picture that as n is getting larger the function is getting more accurate.
Your code's problem is that your x value is your n value, and this is not really true.
x: Must be the value you want to now e^x.
n: Is the accurate of your equation. Larger means more accurate.
So you must change while(x>counter) with while(n>counter), where n can be either a variable with the user selected accuracy, or a constant with your selected accurcy.
I think that until x=100, n=150 should work.
I hope that helps you! :)
There seems to be an answer here: EXP to Taylor series for c++, even though the algorithm is slightly different to yours. Here's its Java version:
public class TaylorSeries {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter x:");
double x = input.nextDouble();
double result = calcExp(x);
System.out.println("calcExp(x) = " + result);
System.out.println(" e^x = " + Math.pow(Math.E, x));
}
static double calcExp(double x) {
double eps = 0.0000000000000000001;
double elem = 1.0;
double sum = 0.0;
boolean negative = false;
int i = 1;
sum = 0.0;
if (x < 0) {
negative = true;
x = -x;
}
do {
sum += elem;
elem *= x / i;
i++;
if (sum > Double.MAX_VALUE) {
System.out.println("Too Large");
break;
}
}
while (elem >= eps);
return negative ? 1.0 / sum : sum;
}
}
The output:
Enter x:
2
calcExp(x) = 7.389056098930649
e^x = 7.3890560989306495
All credit should go to the answer here: EXP to Taylor series. I have only converted c++ code to Java
My code is to print the decimal equivalent of a binary number entered by user.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter a binary integer: ");
int b=in.nextInt();
int digits=1;
int q=b;
//determine the number of digits
while(q/10>=1){
++digits;
q/=10;
}
System.out.println(digits);
int decimal=0;
int i=0;
//pick off the binary number's digits and calculate the decimal equivalent
while(i<=digits-1){
decimal+=b/Math.pow(10,i)%10*Math.pow(2,i);
i++;
}
System.out.println(decimal);
}
}
When I enter 1101, it outputs 13, which is the right answer. However, when I
test the number 11001, the decimal equivalent is supposed to be 25, but it outputs 26. I try
to fix it but can't find where the bug is. Can you guys help me out?
The problem is that Math.pow returns a floating-point number, and you're doing floating-point calculations where you think you're doing integer calculations. When i is 4, and you calculate
b/Math.pow(10,i)%10*Math.pow(2,i);
the calculation goes like this:
b = 11001
b / Math.pow(10,i) = b / 10000 = 1.1001 (not 1)
1.1001 % 10 = 1.1001
1.1001 * Math.pow(2,i) = 1.1001 * 16 = 17.6016 (not 16)
This is then cast to an (int) when you add it to decimal. It truncates the last value to 17, but it's too late.
Casting the Math.pow results to an (int) will make it work. But this isn't the right approach anyway. If you want to learn how to do it yourself instead of using parseInt, it's best to input the number as a String (see my earlier comment), and then you don't have to worry about picking off the bits as decimal digits or powers of 10 at all anyway. Even using your approach, instead of Math.pow it would be simpler to keep powerOf10 and powerOf2 integer variables that you modify with powerOf10 *= 10; powerOf2 *= 2; in each loop iteration.
Try using:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("Enter a binary integer: ");
int b=in.nextInt();
int answer = Integer.parseInt(in.nextInt() + "", 2);
System.out.println("The number is " + answer + ".");
}
}
2 is for base 2.