klasscho

Untitled

Dec 17th, 2019
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.05 KB | None | 0 0
  1. package com.company;
  2. import java.util.Scanner;
  3. import java.io.FileWriter;
  4. import java.io.BufferedReader;
  5. import java.io.InputStreamReader;
  6. public class Main {
  7. public static float Epsilon(double LimitEps) {
  8. boolean isInCorrect = true;
  9. float Eps;
  10. do {
  11. try {
  12. Scanner num = new Scanner(System.in);
  13. Eps = num.nextInt();
  14. if ((Eps > 1) || (Eps < LimitEps)) {
  15. System.out.format("Your number must belong to the range of [%d..%d]!\n",
  16. 0, LimitEps);
  17. } else
  18. isInCorrect = false;
  19. } catch (Exception e) {
  20. System.out.println("Enter a correct value!");
  21. }
  22. }
  23. while (isInCorrect);
  24. return Eps;
  25. }
  26.  
  27. public static float FunctionArgument(double limitX) {
  28. boolean isInCorrect = true;
  29. float x;
  30. do {
  31. try {
  32. Scanner num = new Scanner(System.in);
  33. x = num.nextInt();
  34. if ((x < 0) || (x > limitX)) {
  35. System.out.format("Your number must belong to the range of [%d..%d]!\n",
  36. 0, limitX);
  37. } else
  38. isInCorrect = false;
  39. } catch (Exception e) {
  40. System.out.println("Enter a correct value!");
  41. }
  42. }
  43. while (isInCorrect);
  44. return x;
  45. }
  46.  
  47.  
  48. public static double MaclaurinSeries(float Eps, float x) {
  49. double y = 0.0, value = 0.0;
  50. double factorial = 1.0, power = x, sign = 1.0;
  51. int n = 1;
  52. do {
  53. value = power / factorial;
  54. y += sign * value;
  55. n++;
  56. sign *= -1.0;
  57. power *= x * x;
  58. factorial *= (float) (2 * n - 1) * (2 * n - 2);
  59. } while (value > Eps);
  60. return y;
  61. }
  62.  
  63. public static void Input(float Eps, float x, double result) {
  64. System.out.printf("%.4f ", Eps, x, result);
  65. }
  66.  
  67.  
  68. public static void WriteToFile(double y, String FName) throws Exception {
  69. int n;
  70. FileWriter FileOut = new FileWriter(FName);
  71. for (int i = 0; i < n; i++) {
  72. FileOut.write(y + " ");
  73. }
  74. FileOut.write("\n");
  75. FileOut.close();
  76. System.out.println("Saved to file: " + FName);
  77. }
  78.  
  79. public static void main(String[] args) {
  80. final double LimitEps = 0.000001;
  81. final double LimitX = 124;
  82. String FileNameOut;
  83. double y;
  84. float Eps, x;
  85. BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  86. 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");
  87. Eps = Epsilon(LimitEps);
  88. x = FunctionArgument(LimitX);
  89. y = MaclaurinSeries(Eps, x);
  90. Input(Eps, x, y);
  91. FileNameOut = in.readLine();
  92. WriteToFile(y, FileNameOut);
  93. }
  94. }
Advertisement
Add Comment
Please, Sign In to add comment