Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.Scanner;
- import java.io.FileWriter;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- public class Main {
- public static float Epsilon(double LimitEps) {
- boolean isInCorrect = true;
- float Eps;
- do {
- try {
- Scanner num = new Scanner(System.in);
- Eps = num.nextInt();
- if ((Eps > 1) || (Eps < LimitEps)) {
- System.out.format("Your number must belong to the range of [%d..%d]!\n",
- 0, LimitEps);
- } else
- isInCorrect = false;
- } catch (Exception e) {
- System.out.println("Enter a correct value!");
- }
- }
- while (isInCorrect);
- return Eps;
- }
- public static float FunctionArgument(double limitX) {
- boolean isInCorrect = true;
- float x;
- do {
- try {
- Scanner num = new Scanner(System.in);
- x = num.nextInt();
- if ((x < 0) || (x > limitX)) {
- System.out.format("Your number must belong to the range of [%d..%d]!\n",
- 0, limitX);
- } else
- isInCorrect = false;
- } catch (Exception e) {
- System.out.println("Enter a correct value!");
- }
- }
- while (isInCorrect);
- return x;
- }
- public static double MaclaurinSeries(float Eps, float x) {
- double y = 0.0, value = 0.0;
- double factorial = 1.0, power = x, sign = 1.0;
- int n = 1;
- do {
- value = power / factorial;
- y += sign * value;
- n++;
- sign *= -1.0;
- power *= x * x;
- factorial *= (float) (2 * n - 1) * (2 * n - 2);
- } while (value > Eps);
- return y;
- }
- public static void Input(float Eps, float x, double result) {
- System.out.printf("%.4f ", Eps, x, result);
- }
- public static void WriteToFile(double y, String FName) throws Exception {
- int n;
- FileWriter FileOut = new FileWriter(FName);
- for (int i = 0; i < n; i++) {
- FileOut.write(y + " ");
- }
- FileOut.write("\n");
- FileOut.close();
- System.out.println("Saved to file: " + FName);
- }
- public static void main(String[] args) {
- final double LimitEps = 0.000001;
- final double LimitX = 124;
- String FileNameOut;
- double y;
- float Eps, x;
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- System.out.println("This program calculates the value of a function y = sin(x) with precision e by expanding the function in a Maclaurin series");
- Eps = Epsilon(LimitEps);
- x = FunctionArgument(LimitX);
- y = MaclaurinSeries(Eps, x);
- Input(Eps, x, y);
- FileNameOut = in.readLine();
- WriteToFile(y, FileNameOut);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment