Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.io.IOException;
- import java.util.Scanner;
- import java.io.FileWriter;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- public class Main {
- public static double Epsilon(double LimitEps) {
- boolean isInCorrect = false;
- double Eps;
- do {
- try {
- Scanner num = new Scanner(System.in);
- Eps = num.nextInt();
- if ((Eps < LimitEps) && (Eps > 1)) {
- System.out.format("Your number must belong to the range of [%f..%d]!\n", LimitEps, 0);
- } else
- isInCorrect = true;
- } catch (Exception e) {
- System.out.println("Enter a correct value!");
- Eps = 0.0f;
- isInCorrect = true;
- }
- }
- while (isInCorrect);
- return Eps;
- }
- public static double FunctionArgument(double limitX) {
- boolean isInCorrect = true;
- double x = 0.0f;
- 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(double Eps, double 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 *= (double) (2 * n - 1) * (2 * n - 2);
- } while (value > Eps);
- return y;
- }
- public static void Input(double Eps, double x, double result) {
- System.out.printf("%.4f ", Eps, x, result);
- }
- public static void WriteToFile(double y, String FName) throws Exception {
- FileWriter FileOut = new FileWriter(FName);
- FileOut.write(y + " ");
- 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;
- double 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.");
- System.out.println("Enter the precision value:");
- Eps = Epsilon(LimitEps);
- System.out.println("Enter the value of the function argument:");
- x = FunctionArgument(LimitX);
- y = MaclaurinSeries(Eps, x);
- Input(Eps, x, y);
- try {
- FileNameOut = in.readLine();
- }catch (IOException e){
- FileNameOut = "";
- }
- try {
- WriteToFile(y, FileNameOut);
- }catch (Exception e){
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment