How can I implement this into code I am taking a user input of three separate floats that must add to one (ie .333333,.333333,.333333) those numbers are the probability of a number (-1,0,1) being picked at random.
if( new Random().nextDouble() <= 0.333334){array[i]=randomNumber(-1,0,1)?
Or something along those lines?
The likelihood that three floats will add to exactly 1.0 is very low, because many (most) real numbers cannot be represented exactly as floats. The best you could do is enter two numbers and calculate the third, which would guarantee that they would add up to 1.0.
public static void main(String[] args) {
double[] probs = readProbabilities();
double random = new Random().nextDouble();
int randomNumber;
if (random <= probs[0]) {
randomNumber = -1;
} else if (random <= (probs[0] + probs[1])) {
randomNumber = 0;
} else {
randomNumber = 1;
}
System.out.println("Random Number is " + randomNumber);
}
public static double[] readProbabilities() {
Scanner sc = new Scanner(System.in);
double first, second, third;
System.out.print("Please insert 1st probability: ");
first = sc.nextDouble();
while (first < 0.0 || first > 1.0) {
System.out.print("Must be between 0.0 and 1.0, try again: ");
first = sc.nextDouble();
}
System.out.print("Please insert 2nd probability: ");
second = sc.nextDouble();
while (second < 0.0 || (first + second) > 1.0 ) {
System.out.print("Must be between 0.0 and " + (1.0 - first) + ":");
second = sc.nextDouble();
}
third = 1.0 - (first + second);
System.out.println("3rd Possibility is " + third);
return new double[] {first, second, third};
}
Questions?
Related
import java.util.Scanner;
class FloatDigit {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double n = sc.nextDouble();
int x = (int) n;
int count = 0;
do {
count++;
x = x / 10;
} while (x != 0);
System.out.println("Before Decimal Digits: " + count);
//it gets stuck from here only
do {
count++;
n = n * 10;
} while (n != (int) n);
System.out.println(count + " total digits present in there in number.");
}
}
This goes in an infinite loop for the value: 58.2354/58.234. It is working fine with other values too and longer values too.
If some debug logging is added to the second loop, it can be seen, that when multiplying a double number by 10, there is a tiny error which does not allow the comparison n == (int) n ever become true.
It is actually a known issue that floating-point arithmetics has a certain computation error, so it should be taken into account when comparing the double n to its counterpart with the decimal point shifted right:
do {
count++;
n = n * 10;
System.out.println(count + " - " + n);
} while (Math.abs(n - (int) n) > 1E-7);
System.out.println(count + " total digits present in the number.");
Output:
58.234
Before Decimal Digits: 2
3 - 582.34
4 - 5823.400000000001
5 - 58234.00000000001
5 total digits present in the number.
So, I have already figured out how to calculate the average and number of integers entered; however, I cannot seem to figure out how to figure out the largest, smallest, even and odd numbers. I have tried several things, but it does not work.
Any tips or suggestions? I do not need for you to write anything for me, but a little guidance would be appreciated. (this is for school, do not want to cheat, just need some help).
import java.util.Scanner;
public class Lab4
{
public static void main(String[] args)
{
double large = Integer.MAX_VALUE;
double small = Integer.MIN_VALUE;
double evenCount = 0;
double oddCount = 0;
double foot = 0;
double ball = 0;
double eagles = 0;
System.out.println("Enter positive or negative integers -- enter zero to quit");
Scanner scan = new Scanner(System.in);
boolean philly = false;
while (!philly)
{
eagles = scan.nextDouble();
if (eagles == 0)
{
philly = true;
}
else
{
foot = foot + eagles;
ball++;
}
}
if (eagles%2==0)
{
evenCount++;
System.out.println("The number of even integers is: " + evenCount);
if (eagles%2==1)
oddCount++;
System.out.println("The number of odd integers is: " + oddCount);
if (eagles < small)
small = eagles;
System.out.println("The smallest integer entered is: " + small);
if (eagles > large)
large = eagles;
System.out.println("The largest integer entered is: " + large);
if (ball > 0)
System.out.println("The number of integers entered is: " + ball);
double avg = foot / ball;
System.out.println("Average of integers: " + avg);
}
else
{
System.out.println("No data");
}
}
}
Some tips:
1)
Make all variables of type Integer. You cannot determine odd/even from Double values.
2)
Initialize the large with Integer.MIN_VALUE and small with Integer.MAX_VALUE.
3)
The check for odd/even/smaller/greater should be executed within the while loop.
I have 2 parts of code, the first one being converting fraction to decimal, and the second one being converting decimal to fraction.
However, I have to combine the two piece of code together and I have no idea.I want it to detect the input as either doubles or fraction and convert it to the other.
import java.util.*;
public class ExcerciseEleven {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
if (denominator == 0) {
System.out.println("Can't divide by zero");
}
else {
double fraction = (double)numerator / denominator;
System.out.println(fraction);
}
}
}
public class Fractions {
public static void main(String args[]) {
double decimal;
double originalDecimal;
int LIMIT = 12;
int denominators[] = new int[LIMIT + 1];
int numerator, denominator, temp;
int MAX_GOODNESS = 100;
// Get a number to be converted to a fraction
if (args.length == 1) {
decimal = Double.valueOf(args[0]).doubleValue();
} else {
// No number was given, so just use pi
assert args.length == 0;
decimal = Math.PI;
}
originalDecimal = decimal;
// Display the header information
System.out.println("-------------------------------------------------------");
System.out.println("Program by David Matuszek");
System.out.println("Input decimal number to be converted: " + decimal);
System.out.println();
// Compute all the denominators
System.out.println("All computed denominators:");
int i = 0;
while (i < LIMIT + 1) {
denominators[i] = (int)decimal;
System.out.print(denominators[i] + " ");
decimal = 1.0 / (decimal - denominators[i]);
i = i + 1;
}
System.out.println();
System.out.println();
// Compute the i-th approximation
int last = 0;
while (last < LIMIT) {
// Print out the denominators used in this computation
System.out.print("Using these " + (last + 1) + " denominators: ");
for (int j = 0; j <= last; j++) {
System.out.print(denominators[j] + " ");
}
System.out.println();
// Initialize variables used in computation
numerator = 1;
denominator = 1;
temp = 0;
// Do the computation
int current = last;
while (current >= 0) {
denominator = numerator;
numerator = (numerator * denominators[current]) + temp;
temp = denominator;
current = current - 1;
}
last = last + 1;
// Display results
double value = (double)numerator/denominator;
int goodness = denominators[last];
double error = 100 * Math.abs(value - originalDecimal) / originalDecimal;
System.out.print("fraction = " + (int)numerator + "/" +
(int)denominator);
System.out.print(", value = " + value);
System.out.print(", goodness = " + goodness);
System.out.println(", error = " + (int)error + "%");
System.out.println();
// Exit early if we have reached our goodness criterion
if (Math.abs(goodness) > MAX_GOODNESS) break;
}
}
}
If I was doing it all on one prompt, I would make two static methods Fraction.TryParse(), and I would use the built in Double.TryParse(), if decimal.TryParse returns true then you do in fact have a decimal. If it returns false, then you have a Fraction, therefore you have to use the same string you passed into Decimal.TryParse() in Fraction.TryParse(). Of course you will need some sanity checks in your Fraction.TryParse() method. The prompt could look something like this:
Enter Decimal/Fraction: 3.14
Enter Decimal/Fraction: 1 + 1/2
Enter Decimal/Fraction: 1 1/2
Enter Decimal/Fraction: 1 (1/2)
You see, if you want this all on one line you need some way to be able to delimit the characters, like a space, or brackets, or simply a + sign which would be mathematically accurate. If it is all on one line it also simplifies your program a little bit because you don't have multiple prompts for one object. The "1 (1/2)" input is not technically mathematically accurate, but you can kind of see how the data is supposed to be structured, you just can't be mathematically rigid with that prompt.
Here I am using the fraction one and one half, your implementation doesn't have a mixed number implementation, but you could just input 1/2 or something, just regular fractions.
//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
I can not use the math class when trying to find the answer. I have to use the for loops when calculating the answer.
package Powers;
import TerminalIO.KeyboardReader;
public class powers {
public static void main(String [] args)
{
KeyboardReader reader= new KeyboardReader();
//Variables
int base; //The base number for the calculations
int minE; //The minimum exponent that will be used
int maxE; //The maximum exponent that will be used
int answer; //Weather the user wishes to repeat or not
double result = 1; //The result of the base to the power of the exponent
//Inputs
do { /* Start of repeat */ base = reader.readInt ("Please enter the base. ");
minE = reader.readInt ("Please enter the minimum exponent. ");
maxE = reader.readInt ("Please enter the maximum exponent. ");
//Error Checking
while (minE > maxE) {
System.out.println("There seems to be an error, your minimum exponent is greater then your maximum exponent. Please re-enter your values");
minE = reader.readInt("Enter your minimum exponent. ");
maxE = reader.readInt("Enter your maximum exponent. ");
}
//End of Error Checking
//Calculations
//Output
System.out.println(" Base Exponent Result");
System.out.println();
int expo; //The exponent by which the base will be powered to
for (expo = minE; expo <= maxE; expo++) {
//For exponent being 0
result = 1;
//For exponent being <0
if (expo <0) {
for (int i= minE;i != 0;i = i + 1) {
result = result/base;
}
}
if (expo == 0) {
result = 1 ;
}
//For exponent being 1
if (expo == 1) {
result = base;
}
//For exponent being >1
if (expo > 1) {
for (int i=1;i<=expo;i++) {
result = result*base;
}
}
System.out.println( " " + base + " " + expo + " " + result);
}
System.out.println();
answer = reader.readInt ("Do you wish to repeat? Enter 1 if yes.");
} while (answer == 1); //End of repeat
}
}
An example answer that comes out is
Please enter the base. 2
Please enter the minimum exponent. -2
Please enter the maximum exponent. 2
Base Exponent Result
2 -2 0.25
2 -1 0.25
2 0 1.0
2 1 2.0
2 2 4.0
As you can see only 0 and the positive work, not the negatives.
You did wrong initialization of i. Instead of i= minE change it to i= expo.
for (int i = expo; i != 0; i = i + 1) {
result = result/base;
}
I just added a "counter" on the negative loop. You were always storing a value of "-2" (or the lowest value) on all your calculations for negative values.
You had to add +1 (-2 + 1 = -1) so it divided correctly.
It was just a logic problem
int counter = 0;
for (expo = minE; expo <= maxE; expo++) {
//For exponent being 0
result = 1;
//For exponent being <0
if (expo < 0) {
for (int i = (minE + counter); i != 0; i = i + 1) {
result = result / base;
}
counter++;
}
Example of output:
Base Exponent Result
2 -3 0.125
2 -2 0.25
2 -1 0.5
2 0 1.0
2 1 2.0
2 2 4.0
2 3 8.0