gpt4 book ai didi

c - 使用 OpenMP 的泰勒级数

转载 作者:行者123 更新时间:2023-11-30 16:19:29 26 4
gpt4 key购买 nike

ex = 1 + x + x2/2! + x3/3! + x4/4! + x5/5! +...

我已将 ex(上图)的泰勒级数转换为 OpenMp 程序。所有代码写在下面。

当我通过 Oracle Ubuntu 运行代码时,它可以工作。它给了我 e^0=1,e^1=2.718,e^2=7.389056

但是当我在 Ubuntu 上运行它(不是虚拟的)时,它就无法正常工作。它给了我 e^0=nan,e^1=0.40..,e^2=4.780

输出是完全随机的,因为它并不像我上面提到的那样精确。我需要帮助。

 #include <math.h>
#include <pthread.h>
#include <stdlib.h>

long double x, fact[150], pwr[150], s[1];
int i, term;

void *Power(void *temp) {
int k;
for (k = 0; k < 150; k++) {
pwr[k] = pow(x, k);
//printf("%.2Lf\n", pwr[k]);
}
return pwr;
}

void *Fact(void *temp) {
long double f;
int j;
fact[0] = 1.0;
for (term = 1; term < 150; term++) {
f = 1.0;
for (j = term; j > 0; j--)
f = f * j;
fact[term] = f;
//printf("%.2Lf\n", fact[term]);
}
return fact;
}

void *Exp(void *temp) {
int t;
s[0] = 0;
for (t = 0; t < 150; t++)
s[0] = s[0] + (pwr[t] / fact[t]);
return s;
}

int main(void) {
pthread_t thread1, thread2, thread3;
long double **sum;
printf("Exponential [PROMPT] Enter the value of x (between 0 to 100) (for calculating exp(x)):");
scanf("%Lf", &x);
printf("\nExponential [INFO] Threads creating.....\n");
pthread_create(&thread1, NULL, Power, NULL); //calling power function
pthread_create(&thread2, NULL, Fact, NULL); //calling factorial function
printf("Exponential [INFO] Threads created\n");
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Exponential [INFO] Master thread and terminated threads are joining\n");
printf("Exponential [INFO] Result collected in Master thread\n");
pthread_create(&thread3, NULL, Exp, NULL);
pthread_join(thread3, sum);
printf("\neXPONENTIAL [INFO] Value of exp(%.2Lf) is : %Lf\n\n", x, s[0]);
exit(1);
}

上面的代码最初是为使用线程的 ex 使用的。

#include <math.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
long double x, f, fact[150], pwr[150], s[1];
int i, term, k, j, t;
long double sum;

printf("Exponential [PROMPT] Enter the value of x (between 0 to 100) (for calculating exp(x)):");
scanf("%Lf", &x);
#pragma omp parallel num_threads(10)
#pragma omp for
for (k = 0; k < 150; k++) {
for (int h = 0; h <= k; h++) {
if (h == 0)
x = 1;
else
pwr[k] = pow(x, k);
}
#pragma omp for
for (term = 1; term < 150; term++) {
f = 1.0;
for (j = term; j > 0; j--)
f = f * j;
fact[term] = f;
}
#pragma omp for
for (t = 0; t < 150; t++)
s[0] = s[0] + (pwr[t] / fact[t]);

printf("\neXPONENTIAL [INFO] Value of exp(%.2Lf) is : %Lf\n\n", x, s[0]);
exit(1);
}

上面的代码是将之前的代码转换为 OpenMP。

最佳答案

for (t = 0; t < 150; t++)
s[0] = s[0] + (pwr[t] / fact[t]);

此代码在并行化时,将同时覆盖同一个变量和部分计算结果。这只有在线程以某种方式协调时才能起作用。幸运的是,openmp 有一个专用指令 reduce 用于计算总和,因此您可以轻松解决此问题。

在代码的 pthread 版本中,一个线程执行此计算,因此没有问题。

关于c - 使用 OpenMP 的泰勒级数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55618379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com