15.12.2015, 23:46. Показов 715. Ответов 0
Здравствуйте всем! Я вот только начал знакомится Руби, а мне необходимо портировать программу с Java на Ruby. По программе просчитывается оценка работы системы массового обслуживания, но я пока не могу переписать её сам, не могли бы вы помочь и возможно ли это сделать адекватно? Спасибо заранее. Ниже привожу код на Java
| Java |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
| import java.util.*;
import java.math.*;
public class ReliabilityTheoryProject {
static ArrayList<Double> beginIntervals = new ArrayList<Double>();
static ArrayList<Double> newIntervals = new ArrayList<Double>();
static HashMap<Integer,BigInteger> cache = new HashMap<Integer,BigInteger>();
static double[] vectorAlpha = new double[beginIntervals.size()];
static double q, qAverage;
static final int RO = 100;
static final double EPS = 0.0001;
static final int K = 140;
static int m = 2*K;
static double alphaBegin = 0.8;
//генерация интервалов распределенных экспоненциально с параметром RO
public static ArrayList generator(){
beginIntervals.clear();
newIntervals.clear();
double sum = 0;
label:
for(int i = 0; i < 2000; i++){
double current = Math.random();
double result = (-(1.0 / RO)) * Math.log(current);
beginIntervals.add(result);
sum = sum + result;
if (sum > rangeValue()){
break label;
}
}
return beginIntervals;
}
//факториал числа
public static BigInteger factorial(int n){
BigInteger ret;
if (n == 0) return BigInteger.ONE;
if (null != (ret = cache.get(n))) return ret;
ret = BigInteger.valueOf(n).multiply(factorial(n-1));
cache.put(n, ret);
return ret;
}
//стационарное распределение
public static final BigDecimal StationaryDistribution(){
BigDecimal sum = BigDecimal.valueOf(0);
BigInteger bi;
for (int i = 0; i < K; i++){
BigDecimal bd = BigDecimal.valueOf((RO^i)*Math.exp(-RO));
bi = factorial(i);
BigDecimal fact = new BigDecimal(bi);
sum = sum.add(bd.divide(fact, BigDecimal.ROUND_HALF_UP));
}
return BigDecimal.valueOf(1).subtract(sum);
}
//пороговое значения для генерации интревалов
public static double rangeValue(){
return Math.log(1/EPS);
}
//вектор Alpha для модификации интервалов
public static double[] vectorAlpha(){
double[] alpha = new double[beginIntervals.size()];
double b = (Math.exp(1) - Math.exp(alphaBegin))/(m-1);
double a = Math.exp(alphaBegin) - b;
alpha[0] = Math.log(a + b*0);
for (int i=1; i < m; i++){
alpha[i] = Math.log(a + b*i);
}
for( int i=m; i < beginIntervals.size(); i++){
alpha[i] = 1;
}
return alpha;
}
//получение модифицированных интервалов
public static ArrayList newIntervals(double[] alpha){
for(int i=0; i < beginIntervals.size(); i++){
double newInterval = beginIntervals.get(i)*alpha[i];
newIntervals.add(newInterval);
}
return newIntervals;
}
public static double[] getProbability(){
double[] sum = new double[newIntervals.size()];
double[] prob = new double[newIntervals.size()];
sum[0] = 0;
prob[0] = 0;
for(int i=1; i < newIntervals.size(); i++){
sum[i] = sum[i-1] + newIntervals.get(i);
}
for(int i=1; i < newIntervals.size(); i++){
prob[i] = Math.exp(-sum[i]);
}
return prob;
}
public static double[] recurrentTerm(){
double[] prob = getProbability();
double[][] interim = new double[newIntervals.size()][newIntervals.size()];
double[] s = new double[K-1];
for(int j=0; j < newIntervals.size(); j++){
if (j == 1){
interim[0][j] = 1;
}else{
interim[0][j] = 0;
}
}
for(int i=1; i < newIntervals.size(); i++){
for(int j=0; j < newIntervals.size(); j++){
if (j == 0 || i+2 == j){
interim[i][j] = 0;
}else if(j-1 == 0){
interim[i][j] = (1 - prob[i])*interim[i-1][j];
}else if(i == j+1){
interim[i][j] = prob[i]*interim[i-1][j-1];
}else{
interim[i][j] = prob[i]*interim[i-1][j-1] + (1 - prob[i])*interim[i-1][j];
}
}
}
int index = 2;
for(int j=0; j < K-1; j++){
s[j] = interim[newIntervals.size() - 1][index];
index++;
}
return s;
}
public static double getMark(){
double[] s = recurrentTerm();
double r = 0, p = 1, f1, f2;
for (int i=0; i < s.length; i++){
r = r + s[i];
}
r = 1 - r;
for(int i=1; i < newIntervals.size()- 1; i++){
f1 = RO*Math.exp(-RO*newIntervals.get(i));
f2 = RO*Math.exp(-RO*beginIntervals.get(i));
p = p*((vectorAlpha[i]*f1)/f2);
}
q = r*p;
return q;
}
public static BigDecimal getError(double q){
BigDecimal err;
BigDecimal est = BigDecimal.valueOf(q);
BigDecimal p = StationaryDistribution();
err = est.subtract(p).abs();
return err.divide(p, BigDecimal.ROUND_HALF_UP);
}
public static void show(ArrayList list){
for (int i = 0; i < list.size(); i++){
System.out.print(list.get(i) + " ");
}
}
public static void showArray(double[] array){
for (int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
}
public static void main(String[] args) {
System.out.println("Поехали");
long start = System.currentTimeMillis();
double[] marks = new double[10000];
double sum = 0;
for(int i = 0; i < 10000; i++){
beginIntervals = generator();
vectorAlpha = vectorAlpha();
newIntervals(vectorAlpha);
marks[i] = getMark();
sum = sum + marks[i];
}
qAverage = sum/10000;
System.out.println(getError(qAverage));
System.out.println("Время выполнение программы: " + (System.currentTimeMillis() - start) + "Мсек");
}
} |
|
Добавлено через 3 часа 5 минут
Добрые люди помогли и скинули вот такой код, но проблема в том, что нет вывода! В конце описаны два метода puts, но на экран ничего не выводится. Подскажите, что не так?
| Ruby |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
| class ReliabilityTheoryProject
def initialize()
@beginIntervals = ArrayList[System::Nullable].new()
@newIntervals = ArrayList[System::Nullable].new()
@cache = Hashtable[System::Nullable, System::Numerics::BigInteger].new()
@vectorAlpha = Array.CreateInstance(System::Double, @beginIntervals.size())
@RO = 100
@EPS = 0.0001
@K = 140
@m = 2 * @K
@alphaBegin = 0.8
end
#генерация интервалов распределенных экспоненциально с параметром RO
def ReliabilityTheoryProject.generator()
@beginIntervals.clear()
@newIntervals.clear()
sum = 0
i = 0
while i < 2000
current = Math.random()
result = (-(1.0 / @RO)) * Math.Log(current)
@beginIntervals.add(result)
sum = sum + result
if sum > ReliabilityTheoryProject.rangeValue() then
break
label
end
i += 1
end
return @beginIntervals
end
#факториал числа
def ReliabilityTheoryProject.factorial(n)
if n == 0 then
return BigInteger.ONE
end
if nil != (ret = @cache.get(n)) then
return ret
end
ret = BigInteger.valueOf(n).multiply(ReliabilityTheoryProject.factorial(n - 1))
@cache.put(n, ret)
return ret
end
#стационарное распределение
def ReliabilityTheoryProject.StationaryDistribution()
sum = BigDecimal.valueOf(0)
i = 0
while i < @K
bd = BigDecimal.valueOf((@RO ^ i) * Math.Exp(-@RO))
bi = ReliabilityTheoryProject.factorial(i)
fact = Decimal.new(bi)
sum = sum.add(bd.divide(fact, BigDecimal.ROUND_HALF_UP))
i += 1
end
return BigDecimal.valueOf(1).subtract(sum)
end
#пороговое значения для генерации интревалов
def ReliabilityTheoryProject.rangeValue()
return Math.Log(1 / @EPS)
end
#вектор Alpha для модификации интервалов
def ReliabilityTheoryProject.vectorAlpha()
alpha = Array.CreateInstance(System::Double, @beginIntervals.size())
b = (Math.Exp(1) - Math.Exp(@alphaBegin)) / (@m - 1)
a = Math.Exp(@alphaBegin) - b
alpha[0] = Math.Log(a + b * 0)
i = 1
while i < @m
alpha[i] = Math.Log(a + b * i)
i += 1
end
i = @m
while i < @beginIntervals.size()
alpha[i] = 1
i += 1
end
return alpha
end
#получение модифицированных интервалов
def ReliabilityTheoryProject.newIntervals(alpha)
i = 0
while i < @beginIntervals.size()
newInterval = @beginIntervals.get(i) * alpha[i]
@newIntervals.add(newInterval)
i += 1
end
return @newIntervals
end
def ReliabilityTheoryProject.getProbability()
sum = Array.CreateInstance(System::Double, @newIntervals.size())
prob = Array.CreateInstance(System::Double, @newIntervals.size())
sum[0] = 0
prob[0] = 0
i = 1
while i < @newIntervals.size()
sum[i] = sum[i - 1] + @newIntervals.get(i)
i += 1
end
i = 1
while i < @newIntervals.size()
prob[i] = Math.Exp(-sum[i])
i += 1
end
return prob
end
def ReliabilityTheoryProject.recurrentTerm()
prob = ReliabilityTheoryProject.getProbability()
interim = Array.CreateInstance(System::Double, @newIntervals.size())
@newIntervals.size()
s = Array.CreateInstance(System::Double, @K - 1)
j = 0
while j < @newIntervals.size()
if j == 1 then
interim[0][j] = 1
else
interim[0][j] = 0
end
j += 1
end
i = 1
while i < @newIntervals.size()
j = 0
while j < @newIntervals.size()
if j == 0 or i + 2 == j then
interim[i][j] = 0
elsif j - 1 == 0 then
interim[i][j] = (1 - prob[i]) * interim[i - 1][j]
elsif i == j + 1 then
interim[i][j] = prob[i] * interim[i - 1][j - 1]
else
interim[i][j] = prob[i] * interim[i - 1][j - 1] + (1 - prob[i]) * interim[i - 1][j]
end
j += 1
end
i += 1
end
index = 2
j = 0
while j < @K - 1
s[j] = interim[@newIntervals.size() - 1][index]
index += 1
j += 1
end
return s
end
def ReliabilityTheoryProject.getMark()
s = ReliabilityTheoryProject.recurrentTerm()
r = 0
p = 1
i = 0
while i < s.length
r = r + s[i]
i += 1
end
r = 1 - r
i = 1
while i < @newIntervals.size() - 1
f1 = @RO * Math.Exp(-@RO * @newIntervals.get(i))
f2 = @RO * Math.Exp(-@RO * @beginIntervals.get(i))
p = p * ((@vectorAlpha[i] * f1) / f2)
i += 1
end
@q = r * p
return @q
end
def ReliabilityTheoryProject.getError(q)
est = BigDecimal.valueOf(q)
p = ReliabilityTheoryProject.StationaryDistribution()
err = est.subtract(p).abs()
return err.divide(p, BigDecimal.ROUND_HALF_UP)
end
def ReliabilityTheoryProject.show(list)
i = 0
while i < list.size()
Console.Write(list.get(i) + " ")
i += 1
end
end
def ReliabilityTheoryProject.showArray(array)
i = 0
while i < array.length
Console.Write(array[i] + " ")
i += 1
end
end
def ReliabilityTheoryProject.main(args)
Console.WriteLine("Поехали")
start = System.currentTimeMillis()
marks = Array.CreateInstance(System::Double, 10000)
sum = 0
i = 0
while i < 10000
@beginIntervals = ReliabilityTheoryProject.generator()
@vectorAlpha = ReliabilityTheoryProject.vectorAlpha()
ReliabilityTheoryProject.newIntervals(@vectorAlpha)
marks[i] = ReliabilityTheoryProject.getMark()
sum = sum + marks[i]
i += 1
end
@qAverage = sum / 10000
Console.WriteLine(ReliabilityTheoryProject.getError(@qAverage))
Console.WriteLine("Время выполнение программы: " + (System.currentTimeMillis() - start) + "Мсек")
end
end |
|