Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need to develop a program in Java to solve some integrals. Integrals like this:
I've looked for some functions to do this, in java.Math but I didn't find anything.
Has anyone an idea to get a solution for this? (Maybe some extra libraries or something like that).
The Wikipedia article on Numerical Integration has a section on methods for one-dimensional integrals.
You should have no problem implementing the "trapezoidal" or "rectangle" rule.
The Apache Commons Math library contains, in the Numerical Analysis section, four different numerical integrators:
Romberg's method
Simpson's method
trapezoid method
Legendre-Gauss method
Take a look at JScience
Check out Simpson's Rule on Wikipedia.
/*------------------------------------------------------------------------------------------------------
* Small program that numerically calculates an integral according to
* Simpson's algorithm. Before executing it, you must enter:
* - the expression of the function f: line 12;
* - the lower and upper limits b of the integral: lines 39 and 40;
* - the number of measurements n (n is integer !!!): line 41.
*------------------------------------------------------------------------------------------------------*/
// Class function: Defines Simpson's rule
class Function{
// Define the function to integrate
double f (double x) {
return Math.Cos(x);
}
// Simpson's method for integral calculus
// a = lower bound
// b = upper bound of integration
// n = number of passes (higher = less margin of error, but takes longer)
double IntSimpson(double a, double b,int n){
int i,z;
double h,s;
n=n+n;
s = f(a)*f(b);
h = (b-a)/n;
z = 4;
for(i = 1; i<n; i++){
s = s + z * f(a+i*h);
z = 6 - z;
}
return (s * h)/3;
}
}
class integration{
// Class result: calculates the integral and displays the result.
public static void main(String args[]){
// Call class function
Function function;
function = new Function();
// ENTER the desired values of a, b and n !!!
double a = ???? ;
double b = ???? ;
int n = ???? ;
// Applies simpson method to function
double result = function.IntSimpson(a,b,n);
// Show results
System.out.println("Integral is: " + result);
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a small problem. I think it's simple, but I don't know, how to manage it properly.
I have this simple int:
int birth = 011112;
and I want output to look like this, in this specific format.
"Your birth date is 12.11.01."
I did it with an integer array, but I want only one integer input like this one, not an array.
Could some body help me? Is there any simple method to manage it of, without using loops?
Basically, the conversion of the int representing a date in some format into String should use divide / and modulo % operations, conversion to String may use String.format to provide leading 0.
The number starting with 0 is written in octal notation, where the digits in range 0-7 are used, so the literals like 010819 or 080928 cannot even be written in Java code as int because of the compilation error:
error: integer number too large
int birth = 010819;
However, (only for the purpose of this exercise) we may assume that the acceptable octal numbers start with 01 or 02 then such numbers are below 10000 decimal.
Then the numeric base for division/modulo and the type of output (%d for decimal or %o for octal) can be defined:
public static String rotate(int x) {
int base = x < 10000 ? 0100 : 100;
String type = x < 10000 ? "o" : "d";
int[] d = {
x % base,
x / base % base,
x / (base * base)
};
return String.format("%02" + type + ".%02" + type + ".%02" + type, d[0], d[1], d[2]);
}
Tests:
System.out.println(rotate(011112)); // octal
System.out.println(rotate(11112)); // decimal (no leading 0)
Output:
12.11.01
12.11.01
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
An example will clear the idea:
number A = 12
number B = 20
I need to divide A per 5 until I dont go less than 5. So I get 3 parts: 5,5 an 2.
Now I have to use this result to split B given the weight just calculated.
So 20 * (5/12), 20 * (5/12), 20* (2/12) and their sum of course must be exactly equal to B (20 in our case)
I have to do this without losing any precision and trying to have the result as much correct as possible. My example is using int, but I need to do that with decimals as well.(A could be 12.37 and B could be 20.13 for instance) Anyone knows a library or a hint to do that ?
Well, this question (at least the way I understand it) is pretty simple to solve:
What we've got: A and B, which may be decimal
What we want: a sequence (a1, a2, ..., an) with the following properties:
any element of the sequence is smaller equal 5
all elements sum up to A: a1 + a2 + ... + an = A
a1 / A * B + a2 / A * B + ... + an / A * B = B
Well time for a bit of math:
B = //RHS => LHS
a1 / A * B + a2 / A * B + ... + an / A * B = //factorize
(a1 + a2 + ... + an) / A * B = //(a1 + a2 + ... + an) = A
B
Or in other words: use whatever sequence you like. As long as the elements of the sequence sum up to A and are all smaller-equal to B you're fine.
As for the precision:
Using the type of the input there shouldn't be any issue with precision, as the output can be built in a manner to only consist of integers and the decimal part of the input (so actually your output might have a better -unused - precision than the input).
So to generate the values a1 / A * B, a2 / A * B, ... we need to do the following:
Use BigDecimal for maximum-precision - beware though, as B / A may be periodic! The rest works just the usual way, except that you need to use methods instead of normal operators:
a + b with BigDecimal would be a.add(b)
a * b with BigDecimal would be a.multiply(b)
...
You can look up the details in the documentation.
after reading your question, i cant figure out what is that you want.
Do you want the sequence of 5,5,5,..n(where n<5) for A or B,and also the thing about sum for B is it a condition or is that what you are trying to achieve ?
anyway if its the sequence that you want then you could do this :
int A,B; //if A=12
int numOfFives=A/5; // then numOfFives=2
int remainder=A%5; //then remainder=2
using this method will ensure that the last number will always be less than one.
so you could do the sum like :
sum=0;
for(int i=0;i<numOfFives;i++){
sum+=B*(5d/12d); // 5/12 with sum as int gives result sum =0 , so change the fraction part accordingly to your need.
}
sum+=B*(remainder/12d);
if you want the sequence then do :
System.out.println("Sequence = ");
for(int i=0;i<numOfFives;i++){
System.out.println(5+",");
}
System.out.println(remainder);
also make your calulation of sequence much easier.
Edit 1
here is the Live Program on IdeOne if you want to check it out.
inputs :
A=12
B=20
outputs:
Final Sum=20.0
Sequence=5,5,2
Try out this example:
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Example {
public static void main (String[]args) {
BigDecimal a = new BigDecimal("16.3");
BigDecimal b = new BigDecimal("20");
BigDecimal[] div_rem = a.divideAndRemainder(new BigDecimal("5"));
String s = "";
for (int i = 0; i<div_rem[0].intValue();i++){
s += b +" * (5/"+a+"), ";
}
s += b +" * ("+div_rem[1]+"/"+a+")";
System.out.println(s);
System.out.println(b +" * (5/"+a+") = " + b.multiply(new BigDecimal("5").divide(a, 5,RoundingMode.HALF_UP)));
System.out.println(b +" * ("+div_rem[1]+"/"+a+") = " + b.multiply(div_rem[1].divide(a,5 ,RoundingMode.HALF_UP)));
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Am on generating snippets for built-in functions to know how they are executed, and is a part of my research also. i successfully completed some string handling functions,split, substring,reverse etc.. but i stuck in random numbers how they ware generated? how the RND or Random functions are work?
Thanks in advance
The most popular current algorithm is probably the Mersenne twister, pseudo-code in the Wikipedia article (and there are many implementations available from Google).
Another well known algorithm is Blum Blum Shub which has a proof that reduces its' security to the computational difficulty of computing modular square roots, a problem whose difficulty is assumed to be equivalent to factoring. However Blum Blum Shub is very slow.
Finally, here is a large list of additional pseudo-random number generators. Which algorithm a particular language uses varies.
Here's two algorithms that I've used most often in some of my projects:
1.Uniform distributed numbers in range between 0 and 1
result = getRidOfIntegerPart(A * prevResult)
Where A is a seed.
Possible implementation(C++):
int main()
{
double A = 12.2345; //seed
double prevResult = 1; //You can assign any value here
double result;
double intPart;
//This will give you 10 uniform distributed numbers
for(unsigned i = 0; i < 10; ++i)
{
double r = A * prevResult;
result = modf(r, &intPart); // To get rid of integer part
prevResult = result;
cout<<"result "<<i<<" = "<<result<<endl;
}
}
2. Normal(Gauss) distribution
Here's an original formula:
http://en.wikipedia.org/wiki/Normal_distribution
But I'm using a bit different simplifed formula:
It says that new normal distributed number obtained from sum of 12 uniform distributed numbers(Sj)
Possible implementation(C++):
class RandomNumberGenerator
{
public:
RandomNumberGenerator()
{
uniformPrevResult = 1;
uniformResult = 0;
uniformIntPart = 0;
}
double generateUniformNumber(double seed)
{
double r = seed * uniformPrevResult;
uniformResult = modf(r, &uniformIntPart); // To get rid of integer part
uniformPrevResult = uniformResult;
return uniformResult;
}
double generateNormalNumber(double seed)
{
double uniformSum = 0;
for(unsigned i = 0; i < 12; ++i)
{
uniformSum += generateUniformNumber(seed);
}
double normalResult = uniformSum - 6;
return normalResult; // 6 is a magic number
}
private:
double uniformPrevResult;
double uniformResult;
double uniformIntPart;
};
int main()
{
const double seed = 12.2345;
RandomNumberGenerator rndGen;
for(unsigned i = 0; i < 100; ++i)
{
double newNormalNumber = rndGen.generateNormalNumber(seed);
cout<<"newNormalNumber = "<<newNormalNumber<<endl;
}
return 0;
}
I hope it'll help you!
The JAva languages uses the algorithm that is documented in java.util.Random. There it also states that all implementations must use this algorithm
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
return (int)(seed >>> (48 - bits));
Hence it is not true for Java that "which algorithm a particular language uses varies".
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am reviewing a piece of code that looks like this:
float x = 9;
float y = 5;
int z = (int)(x / y);
Question:
I am wondering why there is a second int on line 3 when it is already declared that z is an int. Thanks in advance.
The result of the division x / y is a float. Java doesn't allow you to assign to an int variable like this, with a narrowing primitive conversion (here, to an int), because this would potentially lose precision. But Java will allow you to do this with an explicit cast, in which Java assumes you know what you're doing.
You have to declare the result (x/y) to be int, otherwise you are trying to set the value of an int variable with a float, which generates a compiler error. This purposeful declaration is required when reducing the precision or range of a number.
According to compilers we are kiddo's.. therefore he(the compiler) wants us to explicitly mention that what we are doing is on purpose and not a mistake, hence we need to specify explicitly..
These are the two scenarios:
1) With (int):
**Program:**
class fox
{
public static void main(String args[])
{
float x = 9;
float y = 5;
int z = (int)(x / y);
System.out.print(z);
}
}
**Output:**
# 1: hide clone input 8 seconds ago
result: success time: 0.07s memory: 380224 kB returned value: 0
input: no
output:
1
2) Without (int):
**Program:**
class fox
{
public static void main(String args[])
{
float x = 9;
float y = 5;
int z = (x / y);
System.out.print(z);
}
}
**Output:**
Main.java:7: error: possible loss of precision
int z = (x / y);
^
required: int
found: float
1 error
# 1: hide clone 6 seconds ago
result: compilation error
// see the compiler cannot understand that we wish to do it purposefully,,
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is it possible to change the meaning of the asterisk symbol (multiplication operator) in Java?
I want to do this:
int ex = 600 * 0.98;
It fails because you can't convert from double to int. Can I make it so that I'm able to convert the double to an integer? Or does the
asterisk only have one meaning that can't be changed?
I just want the OPERATION in math, not a string.
To have an operation, you must have code. One way of doing this is to have a method like
public static double ex(double factor) {
return factor * 0.98;
}
or if the factor is a field
private double factor = 600;
public double ex() {
return factor * 98 / 100;
}
public static void main(String... ignored) {
Main m = new Main();
System.out.println("factor: "+m.factor+" ex: "+ m.ex());
m.factor = 700;
System.out.println("factor: "+m.factor+" ex: "+ m.ex());
}
prints
factor: 600.0 ex: 588.0
factor: 700.0 ex: 686.0
As you can see ex() is re-evaluated each time it is used.
Why do I * 98 / 100? I do this as each value can be represented exactly however 0.98 is not represent exactly and can have a small error.
System.out.println(new BigDecimal(0.98));
prints the closest representable value to 0.98
0.979999999999999982236431605997495353221893310546875
If you want to store text you need to do something like
String ex = "600 * 0.98";
An int value is for storing a whole number which is a 32-bit signed value, nothing else.
Uhhh.
The short answer is that you can't do that. A variable of type int can only store an integer value. The expression you assign to the int has to evaluate to an integer.
What integer value do you want assigned to ex?
int ex = 588; // 600 * 0.98
What meaning are you associating with the asterisk between two numeric values that is not multiplication?
If you want to store an array of characters, then:
char[] ex = "600 * 0.98".toCharArray();