How to use a scanner in a while loop - java

I'm trying to create a method that will return the sum of the nth roots of each double x in numbers, where numbers consists of zero or more double tokens (separated by white space) and n is positive.
Examples: sumOfRoots("1.0 4.0 9.0 16.0", 2) is 10 and sumOfRoots("", 3) is 0.
public static double sumOfRoots (String numbers, int n)
{
Scanner scanner = new Scanner(numbers);
Scanner b = scanner.useDelimiter(" ");
int y = b.nextInt();
double x = 0;
while (b.hasNextDouble())
{
x = x + (y ^ (1 / n));
}
return x;
}
But I keep on throwing input mismatch errors. Any idea on what I can change to make it work?

If you wish to use Scanner, your code can be fixed like that:
public static double sumOfRoots(String numbers, int n){
Scanner scanner = new Scanner(numbers);
double sum = 0;
while(scanner.hasNextDouble())
sum += Math.pow(scanner.nextDouble(), 1d / n);
return sum;
}
In Java ^ is not an exponentional operator (as said in comments), so you have to use Math.pow()

Related

Java program gives incorrect Taylor series term for function e^x

//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

program to convert decimal numbers to another base does not work correctly

I wrote this program to convert decimal numbers to another bases but when I run it with eclipse the answer is 0 for any number.
import java.util.Scanner;
public class dtb {
public static void main(String[] args) {
Scanner myscanner = new Scanner (System.in);
int num= myscanner.nextInt();
int base= myscanner.nextInt();
int i=0;
int y=0;
while (num >= base){
int x = (num%base);
num = num/base;
y = (y + (x*(10^i)));
}
System.out.println (y) ;
}
}
The ^ operator doesn't do what you think. If you want to elevate to a power, use Math.pow():
Math.pow(10, i)
but since this method returns a double, you will have to cast it to int:
(int) Math.pow(10, i)
Check your input. you num value should be greater than base value. eg: 30,20 output is 100.

Does Java have an exponential operator?

Is there an exponential operator in Java?
For example, if a user is prompted to enter two numbers and they enter 3 and 2, the correct answer would be 9.
import java.util.Scanner;
public class Exponentiation {
public static double powerOf (double p) {
double pCubed;
pCubed = p*p;
return (pCubed);
}
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
double num = 2.0;
double cube;
System.out.print ("Please put two numbers: ");
num = in.nextInt();
cube = powerOf(num);
System.out.println (cube);
}
}
There is no operator, but there is a method.
Math.pow(2, 3) // 8.0
Math.pow(3, 2) // 9.0
FYI, a common mistake is to assume 2 ^ 3 is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.
To do this with user input:
public static void getPow(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first integer: "); // 3
int first = sc.nextInt();
System.out.println("Enter second integer: "); // 2
int second = sc.nextInt();
System.out.println(first + " to the power of " + second + " is " +
(int) Math.pow(first, second)); // outputs 9
The easiest way is to use Math library.
Use Math.pow(a, b) and the result will be a^b
If you want to do it yourself, you have to use for-loop
// Works only for b >= 1
public static double myPow(double a, int b){
double res =1;
for (int i = 0; i < b; i++) {
res *= a;
}
return res;
}
Using:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
There is the Math.pow(double a, double b) method. Note that it returns a double, you will have to cast it to an int like (int)Math.pow(double a, double b).
you can use the pow method from the Math class. The following code will output 2 raised to 3 (8)
System.out.println(Math.pow(2, 3));
In case if anyone wants to create there own exponential function using recursion, below is for your reference.
public static double power(double value, double p) {
if (p <= 0)
return 1;
return value * power(value, p - 1);
}

making a range for data points in java

If a user enters a value for
x y and z coordinates, what steps would need to take in order to create a range from -x/y/z to +x/y/z? Is there a function that will give the numbers in that range even though a double is entered?
This is my code so far im not finished yet, I'm not sure if its right. After it gets the x,y,z points and the number of data points the user wants, it will then print the n number of points with random points (x , y, z) x, y, z being anywhere from -x to x etc.
import java.io.*;
public class MultiDimArray
{
public static void main (String [] args) throws IOException
{
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed
double range;
System.out.println("How many points do you want returned? ");
String numPointsA = myInput.readLine();
int numPoints = Integer.parseInt(numPointsA);
System.out.println("Enter X length: ");
String xlengthA = myInput.readLine();
double xlength = Double.parseDouble(xlengthA);
System.out.println("Enter Y length: ");
String ylengthA = myInput.readLine();
double ylength = Double.parseDouble(ylengthA);
System.out.println("Enter Z length: ");
String zlengthA = myInput.readLine();
double zlength = Double.parseDouble(zlengthA);
int[][][][] dataPoint = new int[3][xlength][ylength][zlength];
for (int i = 0; i < (xlength * 2); i++){
range = (0 -( xlength - i) + 1);
System.out.println(range);
}
for (int i = 0; i < (ylength * 2); i++){
range = (0 -( ylength - i) + 1);
}
for (int i = 0; i < (zlength * 2); i++){
range = (0 -( zlength - i) + 1);
}
}
}
range is infinite if you want to include all fractional numbers otherwise you can do that manually.
for (int i=-x; i<=x; i++)
operate(i, y, z);
another solution for your problem is that you don't generate range.
you just store those values x y and z.
then, when you need to test if a number is in range you can do it easily with if statement.
what I mean that this a wrong way to design your solution. try to get values you want in another way. something like reverse engineering. then you test if those values are in range.
post your problem. then we can help you.
Code that generates numPointsA random numbers between -x and x:
Random random = new Random();
double start = -x;
double end = x;
for (int i=0;i<numPointsA;i++)
{
double ran = random.nextDouble();
double result = start + (ran * (end - start));
System.out.println(result);
}
To get a random number between 0 and n-1, use
Random rand = new Random();
int r = rand.nextInt(n);

Fibonacci calculation

This program is supposed to get a Fibonacci number from the user and the program will calculate what it is while making sure that the user entered a positive number and a number no less than the Fibonacci number 70. So, if the user entered 7, it should print 13. The method fibcalc() is supposed to do the calculations.
When I try and compile the program, I get the errors "method fibcalc in class Fibonacci cannot be applied to given types: System.out.printf("Fibonacci #%d is %f", num, fibcalc(num, x3)); and "cannot find symbol" return x3;Here's my code:
import java.util.Scanner;
public class Fibonacci
{
public static void main ( String args[] )
{
Scanner input = new Scanner ( System.in );
int num;
double x3 = 0;
System.out.print("Which Fibonacci number would you like? ");
num = input.nextInt();
do
{
System.out.print("Which Fibonacci number would you like? ");
num = input.nextInt();
}while(num >= 0 && num <= 70);
System.out.printf("Fibonacci #%d is %f", num, fibcalc(num, x3));
}
public static double fibcalc(int num)
{
int x1 = 0;
int x2 = 1;
if (num == 0)
return 0;
else if (num == 1)
return 1;
else
for (int x3 = 0; x3 < num; x3++)
{
x3 = x1 + x2;
x1 = x2;
x2 = x3;
}
return x3;
}
}
There are probably other problems I've missed. I'm pretty new to java. Thanks in advance.
The fibcalc() method has a single int parameter, but you are calling it with two parameters.
Change the call from
fibcalc(num, x3)
to
fibcalc(num)
ie change that line to:
System.out.printf("Fibonacci #%d is %f", num, fibcalc(num));
Also, if you want accurate numbers for your results, change from using double to using BigInteger, which can handle arbitrarily large numbers accurately.
You can also use the following calculator to calculate the Fibonacci sequence (using Javascript): enter link description here
If you want to compute Fibonacci numbers, you can use direct (non-recursive, non-iterative) formula for Fibonacci numbers:
Fib(n) = (pow((1+sqrt(5))/2, n) + pow((1-sqrt(5))/2, n)) / sqrt(5)
It turns out that for all n >= 0, you can simplify this formula to:
Fib(n) = round(pow((1+sqrt(5))/2, n) / sqrt(5))
Knowing this, you can use following simple implementation for fibcalc:
public static double fibcalc(int num) {
return Math.floor(Math.pow((1+Math.sqrt(5))/2, num) / Math.sqrt(5) + 0.5);
}

Categories